package com.mzj.saas.mservice.backlog.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.mzj.saas.commons.*;
import com.mzj.saas.commons.enums.*;
import com.mzj.saas.commons.util.ConvertUtils;
import com.mzj.saas.commons.util.DataUtils;
import com.mzj.saas.commons.vo.redis.TokenRedisVo;
import com.mzj.saas.config.pay.PayConfig;
import com.mzj.saas.mservice.application.entity.HouseAuditSet;
import com.mzj.saas.mservice.application.entity.HousePutRecordsSet;
import com.mzj.saas.mservice.application.repository.HouseAuditSetRepository;
import com.mzj.saas.mservice.application.repository.HousePutRecordsSetRepository;
import com.mzj.saas.mservice.area.entity.Area;
import com.mzj.saas.mservice.area.repository.AreaRepository;
import com.mzj.saas.mservice.backlog.entity.*;
import com.mzj.saas.mservice.backlog.repository.*;
import com.mzj.saas.mservice.backlog.vo.*;
import com.mzj.saas.mservice.bill.entity.RentBill;
import com.mzj.saas.mservice.bill.repository.RentBillRepository;
import com.mzj.saas.mservice.community.entity.Community;
import com.mzj.saas.mservice.community.entity.CommunityBuild;
import com.mzj.saas.mservice.community.entity.CommunityBuildUnit;
import com.mzj.saas.mservice.community.repository.CommunityBuildRepository;
import com.mzj.saas.mservice.community.repository.CommunityBuildUnitRepository;
import com.mzj.saas.mservice.community.repository.CommunityRepository;
import com.mzj.saas.mservice.community.service.CommunityService;
import com.mzj.saas.mservice.eligible.entity.DepartmentHierarchy;
import com.mzj.saas.mservice.eligible.entity.WaitingRentRecord;
import com.mzj.saas.mservice.eligible.repository.WaitingRentRecordRepository;
import com.mzj.saas.mservice.eligible.service.DepartmentHierarchyService;
import com.mzj.saas.mservice.house.entity.House;
import com.mzj.saas.mservice.house.repository.HouseRepository;
import com.mzj.saas.mservice.house.vo.HouseVO;
import com.mzj.saas.mservice.lock.Repository.SmartLockAuthRepository;
import com.mzj.saas.mservice.lock.Repository.SmartLockRepository;
import com.mzj.saas.mservice.lock.entity.SmartLock;
import com.mzj.saas.mservice.lock.entity.SmartLockAuth;
import com.mzj.saas.mservice.lockManager.entity.SmartLockUser;
import com.mzj.saas.mservice.lockManager.repository.SmartLockUserRepository;
import com.mzj.saas.mservice.property.entity.CommunityHouseUser;
import com.mzj.saas.mservice.property.entity.EstateRepairsRecord;
import com.mzj.saas.mservice.property.repository.CommunityHouseUserRepository;
import com.mzj.saas.mservice.sys.entity.AppUser;
import com.mzj.saas.mservice.sys.entity.User;
import com.mzj.saas.mservice.sys.entity.WechatAccount;
import com.mzj.saas.mservice.sys.repository.AppUserRepository;
import com.mzj.saas.mservice.sys.repository.UserRepository;
import com.mzj.saas.mservice.sys.repository.WechatAccountRepository;
import com.mzj.saas.mservice.sys.service.UserService;
import com.mzj.saas.redis.RedisService;
import com.mzj.saas.sdk.pay.alipay.AliPayRequest;
import com.mzj.saas.sdk.pay.vo.AliPay;
import com.mzj.saas.sdk.pay.vo.WxPay;
import com.mzj.saas.sdk.pay.wxpay.WxPayRequest;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.weaver.ast.Var;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
public class BacklogService {
    private static final Logger log = LoggerFactory.getLogger(BacklogService.class);

    private static final String BACKLOG_COUNT = "SELECT COUNT(1) FROM saas_backlog_item b";
    private static final String BACKLOG_COLUM = "SELECT * FROM saas_backlog_item b";
    private static final String BACKLOG_ORDER = " ORDER BY b.create_time DESC";
    private static final String HOUDE_ORDER = " ORDER BY h.create_time DESC";
    private static final String SQL_PAGE = " LIMIT ? OFFSET ?";

    @Autowired
    private RedisService redisService;
    @Autowired
    private PayConfig payConfig;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private AppUserRepository appUserRepository;
    @Autowired
    private BacklogItemRepository backlogItemRepository;
    @Autowired
    private HouseAuditSetRepository houseAuditSetRepository;
    @Autowired
    private HouseRepository houseRepository;
    @Autowired
    private CommunityRepository communityRepository;
    @Autowired
    private CommunityBuildRepository communityBuildRepository;
    @Autowired
    private CommunityBuildUnitRepository communityBuildUnitRepository;
    @Autowired
    private AreaRepository areaRepository;
    @Autowired
    private BacklogItemLockRepository backlogItemLockRepository;
    @Autowired
    private RentBillRepository rentBillRepository;
    @Autowired
    private WechatAccountRepository wechatAccountRepository;
    @Autowired
    private DepartmentHierarchyService departmentHierarchyService;
    @Autowired
    private SmartLockRepository smartLockRepository;
    @Autowired
    private BacklogItemPersonRepository backlogItemPersonRepository;
    @Autowired
    private HousePutRecordsSetRepository housePutRecordsSetRepository;
    @Autowired
    private UserService userService;
    @Autowired
    private BacklogItemRentRepository backlogItemRentRepository;
    @Autowired
    private BacklogItemContractBillRepository backlogItemContractBillRepository;
    @Autowired
    private BacklogItemContractConfirmRepository backlogItemContractConfirmRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private SmartLockUserRepository smartLockUserRepository;
    @Autowired
    private SmartLockAuthRepository smartLockAuthRepository;
    @Autowired
    private WaitingRentRecordRepository waitingRentRecordRepository;
    @Autowired
    private BacklogItemCardRefRepository backlogItemCardRefRepository;
    @Autowired
    private CommunityHouseUserRepository communityHouseUserRepository;
    @Autowired
    private CommunityService communityService;

    @Value("${officialAccount.appId}")
    private String officialAccountAppId;

    public ResultBean<BacklogItemApiData<BacklogListVO>> backlogList(String accessToken, Integer status,
                                                                     Integer pageNumber, Integer pageSize) {
        ResultBean<BacklogItemApiData<BacklogListVO>> resultBean = new ResultBean<>();
        resultBean.setCode("10000");
        resultBean.setMsg("10000");
        BacklogItemApiData<BacklogListVO> apiData = new BacklogItemApiData<>();
        resultBean.setResultData(apiData);
        try {
            if (status == null) {
                return ResultBean.failedResultWithMsg("状态id为空");
            }

            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            String userId = tokenRedisVo.getId();
            Long enterpriseId = tokenRedisVo.getEnterpriseId();
            String phone = tokenRedisVo.getPhone();
            StringBuilder userSql = new StringBuilder();
            StringBuilder Sql = new StringBuilder();
            List<Object> userArgs = new ArrayList<>();
            List<Object> args = new ArrayList<>();

            // 备案确认
            Long areaId = null;
            Integer recordFlag = 0;// 备案确认标识：0否，1是
            HousePutRecordsSet housePutRecordsSet = housePutRecordsSetRepository.findByConfirmorIdAndStatus(userId, 1);
            if (housePutRecordsSet != null && housePutRecordsSet.getAreaId() != null) {
                areaId = housePutRecordsSet.getAreaId();
                recordFlag = 1;
            }

            AppUser user = appUserRepository.findByIdOrEnterpriseUserId(userId, userId);

            Sql.append("SELECT \n" +
                    "  c.`name` AS userName,\n" +
                    "  u.name AS operatorName ,\n" +
                    "  de.name AS orgName, \n" +
                    "  b.`remark` AS remark\n" +
                    "FROM\n" +
                    "  saas_backlog_item a\n" +
                    " LEFT JOIN saas_backlog_item_card b \n" +
                    "    ON b.backlog_item_id = a.id " +
                    "   LEFT JOIN saas_app_user c \n" +
                    "    ON c.id = a.match_user_id \n" +
                    "    OR c.enterprise_user_id = a.match_user_id \n" +
                    "     LEFT JOIN saas_user d \n" +
                    "    ON d.id = a.match_user_id\n" +
                    "  LEFT JOIN saas_user u \n" +
                    "    ON u.id = a.operator_id \n" +
                    "  LEFT JOIN saas_user_department_ref re \n" +
                    "    ON re.`user_id` = u.id \n" +
                    "  LEFT JOIN saas_department de \n" +
                    "    ON de.id = re.dep_id \n" +
                    "WHERE a.id IN \n" +
                    "  (SELECT \n" +
                    "    ca.backlog_item_id \n" +
                    "  FROM\n" +
                    "    saas_backlog_item_card ca \n" +
                    "  WHERE ca.backlog_item_id = a.id \n" +
                    "    AND a.phone = ?) ORDER BY a.create_time DESC \n");
            args.add(phone);
            userSql.append(" where 1 = 1 and ( b.community_id = ? \n" + //#备案确认
                    "or b.phone = ? \n" + //#接收人手机
                    "or b.org_id = ?   \n" +//#机构
                    "or b.id IN (SELECT c.backlog_item_id FROM saas_backlog_item_contract c WHERE c.match_user_id = ?) \n" + //#合同到期提醒
                    "or b.id IN (SELECT l.backlog_item_id FROM saas_backlog_item_lock l WHERE l.match_user_id = ? ) \n" + //#(智能锁)租金/押金账单
                    "or b.id IN (SELECT ib.backlog_item_id FROM saas_backlog_item_battery ib WHERE ib.match_user_id = ? ) \n" + //#门锁低电量告警
                    "or b.id IN (SELECT o.backlog_item_id FROM saas_backlog_item_lock_off o WHERE o.match_user_id = ? ) \n" + //#门锁离线
                    "or b.id IN (SELECT ia.backlog_item_id FROM saas_backlog_item_approve ia WHERE ia.user_id = ? ) \n" + //#资格申请-审批
                    "or b.id IN (SELECT u.backlog_item_id FROM saas_backlog_item_unopen u WHERE u.match_user_id = ? ) \n" + //#未开门提醒
                    "or b.id IN (SELECT cs.backlog_item_id FROM saas_backlog_item_contract_sign cs WHERE cs.match_user_id = ? ) \n" + //#公租房合同待签约
                    "or b.id IN (SELECT ca.backlog_item_id FROM saas_backlog_item_card ca where ca.backlog_item_id = b.id and ( b.match_user_id = ?  or b.phone = ?) ) \n" + //#CUP卡冻结/解冻
                    "or b.id IN (SELECT bi.backlog_item_id FROM saas_backlog_item_bill bi WHERE bi.backlog_item_id= b.id and  ( b.match_user_id = ?  or b.phone = ?) ) \n" + //#账单- 催缴费
                    "or b.id IN (SELECT rs.backlog_item_id FROM saas_backlog_item_record_submit rs WHERE rs.match_user_id = ? )\n" + //#备案待提交
                    "or b.id IN (SELECT hu.backlog_item_id FROM saas_backlog_item_house_user hu WHERE hu.backlog_item_id = b.id and ( b.match_user_id =?  or b.phone = ?) ) \n" + //#房产成员新增/删除
                    "or b.id IN (SELECT cb.backlog_item_id FROM saas_backlog_item_contract_bill cb WHERE cb.match_user_id = ? ) # 公租房(合同) 租金/押金账单\n" +
                    "or b.id IN (SELECT ob.backlog_item_id FROM saas_backlog_item_house_other_bill ob WHERE ob.backlog_item_id = b.id and ( b.match_user_id =?  or b.phone = ?) ) \n" + //# 公租房其他收费项目账单
                    "or b.id IN (SELECT rb.backlog_item_id FROM saas_backlog_item_property_rent_bill rb WHERE rb.backlog_item_id = b.id and ( b.match_user_id =?  or b.phone = ?) ) \n" + //#非公租房（房产） 租金/押金账单
                    "or b.id IN (SELECT pob.backlog_item_id FROM saas_backlog_item_property_other_bill pob WHERE pob.backlog_item_id = b.id and ( b.match_user_id =?  or b.phone = ?) ) \n" + //# 非公租房（房产） 其他费用账单
                    " ) ");

            userArgs.add(areaId);// 备案确认
            userArgs.add(user.getPhone());// 接收人手机
            userArgs.add(enterpriseId);// 机构
            userArgs.add(userId);// 合同到期提醒 接收人ID
            userArgs.add(userId);//(智能锁)租金/押金账单 接收人ID
            userArgs.add(userId);// 门锁低电量告警 接收人ID
            userArgs.add(userId);// 门锁离线 接收人ID
            userArgs.add(userId);// 资格申请-审批 接收人ID
            userArgs.add(userId);// 未开门提醒  接收人ID
            userArgs.add(userId);// 公租房合同待签约  接收人ID
            userArgs.add(userId);// CUP卡冻结/解冻 接收人ID
            userArgs.add(user.getPhone());// CUP卡冻结/解冻 接收人人手机
            userArgs.add(userId);// 账单- 催缴费 接收人ID
            userArgs.add(user.getPhone());// 账单- 催缴费 接收人人手机
            userArgs.add(userId);// 备案待提交 接收人ID
            userArgs.add(userId);// 房产成员新增/删除 接收人ID
            userArgs.add(user.getPhone());// 房产成员新增/删除 接收人人手机
            userArgs.add(userId);// 公租房(合同) 租金/押金账单  接收人ID
            userArgs.add(userId);// 公租房其他收费项目账单 接收人ID
            userArgs.add(user.getPhone());// 公租房其他收费项目账单 接收人人手机
            userArgs.add(userId);// 非公租房（房产）租金/押金账单 接收人ID
            userArgs.add(user.getPhone());// 非公租房（房产）租金/押金账单 接收人人手机
            userArgs.add(userId);// 非公租房（房产）其他费用账单  接收人ID
            userArgs.add(user.getPhone());// 非公租房（房产）其他费用账单  接收人人手机

            // 判断用户是否公租房绑定审批人，是就查绑定的待办事项，不是就不查
            Integer auditFlag = 0;// 审批人标识：0不是审批人，1是审批人
            if (enterpriseId != null) {
                HouseAuditSet houseAuditSet = houseAuditSetRepository.findByOrgIdAndStatus(enterpriseId, 1);
                if (houseAuditSet != null && userId.equals(houseAuditSet.getAuditId())) {
                    auditFlag = 1;
                }
            }
            // 备案确认标识：0否，1是
            if (recordFlag == 0) {
                userSql.append(" and b.type != 5");
            }
            // if (auditFlag == 0) {
            //    userSql.append(" and b.type != 1");
            //}

            // 全部待办事项总记录数
            Long total = jdbcTemplate.queryForObject(BACKLOG_COUNT + userSql, userArgs.toArray(), Long.class);
            log.info(BACKLOG_COLUM + userSql + userArgs.toArray());
            if (total == 0) {
                return resultBean;
            }
            // 待我处理的总数
            Long pendingTotal = jdbcTemplate.queryForObject(BACKLOG_COUNT + userSql + " and b.handle_status = 0", userArgs.toArray(), Long.class);
            // 我发起的总数
            Long launchTotal = jdbcTemplate.queryForObject(BACKLOG_COUNT + userSql + " and b.operator_id ='" + userId + "'", userArgs.toArray(), Long.class);
            // 我参与的总数
            Long participateTotal = jdbcTemplate.queryForObject(BACKLOG_COUNT + userSql + " and b.handle_status = 2", userArgs.toArray(), Long.class);
            // 已完成总数
            Long doneTotal = jdbcTemplate.queryForObject(BACKLOG_COUNT + userSql + " and b.handle_status = 1", userArgs.toArray(), Long.class);

            StringBuilder where = new StringBuilder();
            if (status == 1) {// 待我处理的
                where.append(" and b.handle_status = ?");
                userArgs.add(0);
            } else if (status == 2) {// 我发起的
                where.append(" and b.operator_id = ?");
                userArgs.add(userId);
            } else if (status == 3) {// 我参与的
                where.append(" and b.handle_status = ?");
                userArgs.add(2);
            } else if (status == 4) {// 已完成的
                where.append(" and b.handle_status = ?");
                userArgs.add(1);
            }

            userArgs.add(pageSize);
            userArgs.add(pageNumber * pageSize);
            args.add(pageSize);
            args.add(pageNumber * pageSize);
            // 待办事项集合
            List<BacklogListVO> list = new ArrayList<>();
            // 判断是否是首页请求还是列表请求
            if (pageSize > 4) {
                List<BacklogItem> backlogItems = jdbcTemplate.query(BACKLOG_COLUM + userSql + where + BACKLOG_ORDER + SQL_PAGE,
                        new BeanPropertyRowMapper<>(BacklogItem.class), userArgs.toArray());
                log.info(BACKLOG_COLUM + userSql + where + BACKLOG_ORDER + SQL_PAGE + userArgs.toArray());
                list = backlogItems.stream().map(backlogItem -> {
                    BacklogListVO vo = new BacklogListVO();
                    vo.setId(backlogItem.getId());
                    vo.setHouseId(backlogItem.getHouseId());
                    vo.setOrgId(backlogItem.getOrgId());
                    Integer type = backlogItem.getType();
                    vo.setType(type);
                    vo.setTitle(backlogItem.getTitle());
                    vo.setContent(backlogItem.getContent());
                    vo.setBusinessStatus(backlogItem.getBusinessStatus());
                    vo.setHandleStatus(backlogItem.getHandleStatus());
                    Date createTime = backlogItem.getCreateTime();
                    vo.setCreateTime(createTime == null ? "" : DateUtils.format(createTime, DateUtils.FORMAT_DATETIME_14));
                    vo.setApplyType(backlogItem.getApplyType());
                    vo.setShortUrl(backlogItem.getShortUrl());

                    // 申请人
                    if (type == BacklogItemTypeEnum.LOCK_BIND.getValue() || type == BacklogItemTypeEnum.ELIGIBLE_APPROVE.getValue()) {
                        vo.setApplyUserId(backlogItem.getOperatorId());
                    } else {
                        vo.setApplyUserId(backlogItem.getMatchUserId());
                    }
                    // 申请单位
                    if (type == BacklogItemTypeEnum.HOUSE_SAVE.getValue()) {
                        vo.setApplyUser(userService.findUserEnterpriseName(backlogItem.getOperatorId()));
                    }

                    return vo;
                }).collect(Collectors.toList());
            } else {
                // 如果有未读的就先返回未读的
                if (pendingTotal > 0) {
                    where.append(" and b.handle_status = 0");
                    List<BacklogItem> backlogItems = jdbcTemplate.query(BACKLOG_COLUM + userSql + where + BACKLOG_ORDER + SQL_PAGE,
                            new BeanPropertyRowMapper<>(BacklogItem.class), userArgs.toArray());
                    list = backlogItems.stream().map(backlogItem -> {
                        BacklogListVO vo = new BacklogListVO();
                        vo.setId(backlogItem.getId());
                        vo.setHouseId(backlogItem.getHouseId());
                        vo.setOrgId(backlogItem.getOrgId());
                        Integer type = backlogItem.getType();
                        vo.setType(type);
                        vo.setTitle(backlogItem.getTitle());
                        vo.setContent(backlogItem.getContent());
                        vo.setBusinessStatus(backlogItem.getBusinessStatus());
                        vo.setHandleStatus(backlogItem.getHandleStatus());
                        Date createTime = backlogItem.getCreateTime();
                        vo.setCreateTime(createTime == null ? "" : DateUtils.format(createTime, DateUtils.FORMAT_DATETIME_14));
                        vo.setApplyType(backlogItem.getApplyType());
                        vo.setShortUrl(backlogItem.getShortUrl());
                        vo.setUserName(null);
                        vo.setOperatorName(null);
                        vo.setOrgName(null);
                        // 申请人
                        if (type == BacklogItemTypeEnum.LOCK_BIND.getValue() || type == BacklogItemTypeEnum.ELIGIBLE_APPROVE.getValue()) {
                            vo.setApplyUserId(backlogItem.getOperatorId());
                        } else {
                            vo.setApplyUserId(backlogItem.getMatchUserId());
                        }
                        // 申请单位
                        if (type == BacklogItemTypeEnum.HOUSE_SAVE.getValue()) {
                            vo.setApplyUser(userService.findUserEnterpriseName(backlogItem.getOperatorId()));
                        }

                        return vo;
                    }).collect(Collectors.toList());
                } else {
                    List<BacklogItem> backlogItems = jdbcTemplate.query(BACKLOG_COLUM + userSql + where + BACKLOG_ORDER + SQL_PAGE,
                            new BeanPropertyRowMapper<>(BacklogItem.class), userArgs.toArray());
                    // List<BacklogListVO> backlogListVOS = jdbcTemplate.query(Sql +SQL_PAGE,
                    //         new BeanPropertyRowMapper<>(BacklogListVO.class), args.toArray());
                    list = backlogItems.stream().map(backlogItem -> {
                        BacklogListVO vo = new BacklogListVO();
                        vo.setId(backlogItem.getId());
                        vo.setHouseId(backlogItem.getHouseId());
                        vo.setOrgId(backlogItem.getOrgId());
                        Integer type = backlogItem.getType();
                        vo.setType(type);
                        vo.setTitle(backlogItem.getTitle());
                        vo.setContent(backlogItem.getContent());
                        vo.setBusinessStatus(backlogItem.getBusinessStatus());
                        vo.setHandleStatus(backlogItem.getHandleStatus());
                        Date createTime = backlogItem.getCreateTime();
                        vo.setCreateTime(createTime == null ? "" : DateUtils.format(createTime, DateUtils.FORMAT_DATETIME_14));
                        vo.setApplyType(backlogItem.getApplyType());
                        vo.setShortUrl(backlogItem.getShortUrl());

                        // 申请人
                        if (type == BacklogItemTypeEnum.LOCK_BIND.getValue() || type == BacklogItemTypeEnum.ELIGIBLE_APPROVE.getValue()) {
                            vo.setApplyUserId(backlogItem.getOperatorId());
                        } else {
                            vo.setApplyUserId(backlogItem.getMatchUserId());
                        }
                        // 申请单位
                        if (type == BacklogItemTypeEnum.HOUSE_SAVE.getValue()) {
                            vo.setApplyUser(userService.findUserEnterpriseName(backlogItem.getOperatorId()));
                        }

                        return vo;
                    }).collect(Collectors.toList());
                }
            }


            // 查询申请人名称
            List<String> ids = list.stream().filter(vo -> StringUtils.isNotBlank(vo.getApplyUserId())).map(BacklogListVO::getApplyUserId).distinct().collect(Collectors.toList());
            if (!ids.isEmpty()) {
                List<AppUser> appUsers = appUserRepository.findByIdOrEnterpriseIn(ids, ids);
                List<User> users = userRepository.findByIdIn(ids);
                for (BacklogListVO vo : list) {
                    String applyUserId = vo.getApplyUserId();
                    if (StringUtils.isNotBlank(applyUserId)) {
                        for (AppUser appUser : appUsers) {
                            if (applyUserId.equals(appUser.getId()) || applyUserId.equals(appUser.getEnterpriseUserId())) {
                                vo.setApplyUser(appUser.getName());
                                break;
                            }
                        }
                        if (StringUtils.isBlank(vo.getApplyUser())) {
                            for (User u : users) {
                                if (applyUserId.equals(u.getId())) {
                                    vo.setApplyUser(u.getName());
                                    break;
                                }
                            }
                        }
                    }
                }
            }

            // 如果有配租待办事项，查询待配租小区id
            List<Long> backlogItemIds = list.stream().filter(v -> v.getType() != null && v.getType() == 4).map(m -> m.getId()).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(backlogItemIds)) {
                List<BacklogItemRent> backlogItemRentList = backlogItemRentRepository.findByBacklogItemIdIn(backlogItemIds);
                if (!backlogItemRentList.isEmpty()) {
                    for (BacklogListVO vo : list) {
                        if (vo.getType() != null && vo.getType() == 4) {
                            for (BacklogItemRent backlogItemRent : backlogItemRentList) {
                                if (backlogItemRent.getBacklogItemId() != null && backlogItemRent.getBacklogItemId().longValue() == vo.getId().longValue()) {
                                    vo.setResidenceCommunityId(backlogItemRent.getResidenceCommunityId());
                                }
                            }
                        }
                    }
                }
            }

            // 获得账单ID ，和类型
            for (BacklogListVO vo : list) {
                String billId = null;
                Integer billType = null; // 账单类型  1 .公租房 租金押金  2. 公租房其他费用 3.房产 租金押金 4.房产其他费用
                /**
                 *   2-智能锁冻结(公租房 租金/押金)
                 *   18- 公租房 (合同)租金押金
                 *    36 公租房(合同) 租金/押金账单
                 */
                String sql = null;
                if (vo.getType() == 2) {
                    sql = " select \n" +
                            "b.bill_id as billId ,\n" +
                            "sc.name AS residenceCommunityName,\n" +
                            "scb.name AS buildingNumName,\n" +
                            "scbu.name AS unitName,\n" +
                            "sh.room_number AS roomnumber ,\n" +
                            "c.payment_time as paymentTime,\n" +
                            "c.cost as money\n" +
                            "from  saas_backlog_item a\n" +
                            "LEFT JOIN saas_backlog_item_lock b on b.backlog_item_id = a.id \n" +
                            "LEFT JOIN saas_rent_bill c on c.id = b.bill_id\n" +
                            " LEFT JOIN saas_house sh    ON sh.id = c.house_id\n" +
                            "LEFT JOIN saas_community sc ON sh.residence_community_id = sc.id\n" +
                            "LEFT JOIN saas_community_build scb ON sh.building_num = scb.id \n" +
                            "LEFT JOIN saas_community_build_unit scbu ON sh.unit = scbu.id \n" +
                            "where a.id= " + vo.getId();
                    List<BacklogVo> backlogVo = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(BacklogVo.class));
                    if (null != backlogVo && backlogVo.size() > 0) {
                        BacklogVo backlogVo1 = backlogVo.get(0);
                        billId = backlogVo1.getBillId();
                        vo.setHouseInfo(backlogVo1.getResidenceCommunityName() + "-" +
                                backlogVo1.getBuildingNumName() + "-" + backlogVo1.getUnitName() + "-" + backlogVo1.getRoomnumber());// 房屋信息
                        vo.setMoney(fenToYuan(backlogVo1.getMoney()));// 金额
                        vo.setPaymentTime(backlogVo1.getPaymentTime());// 缴费时间


                    }
                    billType = 1;
                }

                if (vo.getType() == 18 || vo.getType() == 36) {
                    sql = "select IFNULL(b.rent_bill_id,b.deposit_bill_id) as billId ,\n" +
                            "sc.name AS residenceCommunityName,\n" +
                            "scb.name AS buildingNumName,\n" +
                            "scbu.name AS unitName,\n" +
                            "sh.room_number AS roomnumber ,\n" +
                            "c.payment_time as paymentTime,\n" +
                            "c.cost as money\n" +
                            "from  saas_backlog_item a\n" +
                            "LEFT JOIN saas_backlog_item_contract_bill b on b.backlog_item_id = a.id\n" +
                            "LEFT JOIN saas_rent_bill c on c.id = b.rent_bill_id or  c.id = b.deposit_bill_id\n" +
                            " LEFT JOIN saas_house sh    ON sh.id = c.house_id\n" +
                            "LEFT JOIN saas_community sc ON sh.residence_community_id = sc.id\n" +
                            "LEFT JOIN saas_community_build scb ON sh.building_num = scb.id \n" +
                            "LEFT JOIN saas_community_build_unit scbu ON sh.unit = scbu.id \n" +
                            "where a.id= " + vo.getId();

                    List<BacklogVo> backlogVo = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(BacklogVo.class));
                    if (null != backlogVo && backlogVo.size() > 0) {
                        BacklogVo backlogVo1 = backlogVo.get(0);
                        billId = backlogVo1.getBillId();
                        vo.setHouseInfo(backlogVo1.getResidenceCommunityName() + "-" +
                                backlogVo1.getBuildingNumName() + "-" + backlogVo1.getUnitName() + "-" + backlogVo1.getRoomnumber());// 房屋信息
                        vo.setMoney(fenToYuan(backlogVo1.getMoney()));// 金额
                        vo.setPaymentTime(backlogVo1.getPaymentTime());// 缴费时间
                    }
                    billType = 1;
                }

                // 获得公租房其他账单 saas_backlog_item_house_other_bill
                if (vo.getType() == 37 || vo.getType() == 42) {
                    sql = "select b.bill_id as billId ,\n" +
                            "sc.name AS residenceCommunityName,\n" +
                            "scb.name AS buildingNumName,\n" +
                            "scbu.name AS unitName,\n" +
                            "sh.room_number AS roomnumber ,\n" +
                            "c.payment_time as paymentTime,\n" +
                            "c.cost as money\n" +
                            "from  saas_backlog_item a\n" +
                            "LEFT JOIN saas_backlog_item_house_other_bill b on b.backlog_item_id = a.id \n" +
                            "LEFT JOIN saas_expense_bill c on c.id = b.bill_id \n" +
                            " LEFT JOIN saas_house sh   ON sh.id = c.house_id\n" +
                            "LEFT JOIN saas_community sc ON sh.residence_community_id = sc.id\n" +
                            "LEFT JOIN saas_community_build scb ON sh.building_num = scb.id \n" +
                            "LEFT JOIN saas_community_build_unit scbu ON sh.unit = scbu.id \n" +
                            "  where a.id =" + vo.getId();

                    List<BacklogVo> backlogVo = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(BacklogVo.class));
                    if (null != backlogVo && backlogVo.size() > 0) {
                        BacklogVo backlogVo1 = backlogVo.get(0);
                        billId = backlogVo1.getBillId();
                        vo.setHouseInfo(backlogVo1.getResidenceCommunityName() + "-" +
                                backlogVo1.getBuildingNumName() + "-" + backlogVo1.getUnitName() + "-" + backlogVo1.getRoomnumber());// 房屋信息
                        vo.setMoney(fenToYuan(backlogVo1.getMoney()));// 金额
                        vo.setPaymentTime(backlogVo1.getPaymentTime());// 缴费时间

                    }
                    billType = 2;
                }


                // 获得非公租房（房产） / 租金押金账单 saas_backlog_item_property_rent_bill
                if (vo.getType() == 38) {
                    sql = "select IFNULL(b.rent_bill_id,b.deposit_bill_id) as billId ,\n" +
                            "sc.name AS residenceCommunityName,\n" +
                            "scb.name AS buildingNumName,\n" +
                            "scbu.name AS unitName,\n" +
                            "sh.room_number AS roomnumber ,\n" +
                            "c.payment_time as paymentTime,\n" +
                            "c.cost as money\n" +
                            "from  saas_backlog_item a\n" +
                            "LEFT JOIN saas_backlog_item_property_rent_bill b on b.backlog_item_id = a.id \n" +
                            "LEFT JOIN saas_estate_rent_bill c on c.id = b.rent_bill_id or  c.id = b.deposit_bill_id\n" +
                            "LEFT JOIN saas_house sh    ON sh.id = c.house_id\n" +
                            "LEFT JOIN saas_community sc ON sh.residence_community_id = sc.id\n" +
                            "LEFT JOIN saas_community_build scb ON sh.building_num = scb.id \n" +
                            "LEFT JOIN saas_community_build_unit scbu ON sh.unit = scbu.id \n" +
                            "where a.id=" + vo.getId();

                    List<BacklogVo> backlogVo = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(BacklogVo.class));
                    if (null != backlogVo && backlogVo.size() > 0) {
                        BacklogVo backlogVo1 = backlogVo.get(0);
                        billId = backlogVo1.getBillId();
                        vo.setHouseInfo(backlogVo1.getResidenceCommunityName() + "-" +
                                backlogVo1.getBuildingNumName() + "-" + backlogVo1.getUnitName() + "-" + backlogVo1.getRoomnumber());// 房屋信息
                        vo.setMoney(fenToYuan(backlogVo1.getMoney()));// 金额
                        vo.setPaymentTime(backlogVo1.getPaymentTime());// 缴费时间
                    }
                    billType = 3;
                }

                // 获得非公租房（房产）其他账单 saas_backlog_item_property_rent_bill
                if (vo.getType() == 39 || vo.getType() == 41) {
                    sql = "select b.bill_id as billId ,\n" +
                            "sc.name AS residenceCommunityName,\n" +
                            "scb.name AS buildingNumName,\n" +
                            "scbu.name AS unitName,\n" +
                            "sh.room_number AS roomnumber ,\n" +
                            "c.payment_time as paymentTime,\n" +
                            "c.cost as money\n" +
                            "from  saas_backlog_item a\n" +
                            "LEFT JOIN saas_backlog_item_property_other_bill b on b.backlog_item_id = a.id \n" +
                            "LEFT JOIN saas_estate_expense_bill c on c.id = b.bill_id \n" +
                            "LEFT JOIN saas_house sh    ON sh.id = c.house_id\n" +
                            "LEFT JOIN saas_community sc ON sh.residence_community_id = sc.id\n" +
                            "LEFT JOIN saas_community_build scb ON sh.building_num = scb.id \n" +
                            "LEFT JOIN saas_community_build_unit scbu ON sh.unit = scbu.id \n" +
                            "where a.id=" + vo.getId();

                    List<BacklogVo> backlogVo = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(BacklogVo.class));
                    if (null != backlogVo && backlogVo.size() > 0) {
                        BacklogVo backlogVo1 = backlogVo.get(0);
                        billId = backlogVo1.getBillId();
                        vo.setHouseInfo(backlogVo1.getResidenceCommunityName() + "-" +
                                backlogVo1.getBuildingNumName() + "-" + backlogVo1.getUnitName() + "-" + backlogVo1.getRoomnumber());// 房屋信息
                        vo.setMoney(fenToYuan(backlogVo1.getMoney()));// 金额
                        vo.setPaymentTime(backlogVo1.getPaymentTime());// 缴费时间
                    }
                    billType = 4;
                }

                // 催缴待办事项
                if (vo.getType() == 40) {
                    sql = "select * from  (select a.id ,IFNULL(b.rent_bill_id,b.deposit_bill_id) as billId, 3 AS billType ,if (c.charge_type= 1 ,8,9) as chargeType from  saas_backlog_item a \n" +
                            "LEFT JOIN saas_backlog_item_property_rent_bill b on b.backlog_item_id =a.id \n" +
                            "LEFT JOIN saas_estate_rent_bill c on c.id =b.rent_bill_id or  c.id =b.deposit_bill_id \n" +
                            "UNION  \n" +
                            "select a.id ,b.bill_id as billId , 4 AS billType ,c.charge_type as chargeType from  saas_backlog_item a \n" +
                            "LEFT JOIN saas_backlog_item_bill b on b.backlog_item_id =a.id \n" +
                            "LEFT JOIN saas_estate_expense_bill c on c.id =b.bill_id\n" +
                            ") t1 where t1.id=" + vo.getId() + " and billId is not null ";

                    List<BacklogListVO> backlogListVOS = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(BacklogListVO.class));
                    if (null != backlogListVOS && backlogListVOS.size() > 0) {
                        billId = backlogListVOS.get(0).getBillId();
                        billType = backlogListVOS.get(0).getBillType();
                        vo.setChargeType(backlogListVOS.get(0).getChargeType());
                    }
                }
                // 成员变更 添加字段
                if (vo.getType() == 30 || vo.getType() == 31) {
                    sql = " select sc.name AS residenceCommunityName,\n" +//
                            "scb.name AS buildingNumName,\n" +
                            "scbu.name AS unitName,\n" +
                            "sh.room_number AS roomnumber ,\n" +
                            "c.name as userName,\n" +
                            "c.mobile,\n" +
                            "c.type as userType\n" +
                            "from saas_backlog_item a\n" +
                            "LEFT JOIN saas_backlog_item_house_user b on b.backlog_item_id = a.id \n" +
                            "LEFT JOIN saas_community_house_user c on c.id =  b.house_user_id\n" +
                            "LEFT JOIN saas_house sh       ON sh.id = c.community_house_id\n" +
                            "LEFT JOIN saas_community sc ON sh.residence_community_id = sc.id\n" +
                            "LEFT JOIN saas_community_build scb ON sh.building_num = scb.id LEFT JOIN saas_community_build_unit scbu ON sh.unit = scbu.id \n" +
                            "where a.id=" + vo.getId();
                    List<BacklogVo> backlogVo = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(BacklogVo.class));
                    if (null != backlogVo && backlogVo.size() > 0) {
                        BacklogVo backlogVo1 = backlogVo.get(0);
                        vo.setMobile(backlogVo1.getMobile());// 手机号
                        vo.setUserName(backlogVo1.getUserName());// 姓名
                        vo.setUserType(backlogVo1.getUserType());// 人员类型
                        vo.setHouseInfo(backlogVo1.getResidenceCommunityName() + "-" +
                                backlogVo1.getBuildingNumName() + "-" + backlogVo1.getUnitName() + "-" + backlogVo1.getRoomnumber());// 房屋信息
                    }

                }
                // 智能锁冻结
                if (vo.getType() == 32 || vo.getType() == 33 || vo.getType() == 34 || vo.getType() == 35) {
                    sql = "select sc.name AS residenceCommunityName, \n" +
                            "scb.name AS buildingNumName, \n" +
                            "scbu.name AS unitName, \n" +
                            "sh.room_number AS roomnumber \n" +
                            "from saas_backlog_item a \n" +
                            "LEFT JOIN saas_house sh       ON sh.id = a.house_id \n" +
                            "LEFT JOIN saas_community sc ON sh.residence_community_id = sc.id \n" +
                            "LEFT JOIN saas_community_build scb ON sh.building_num = scb.id LEFT JOIN saas_community_build_unit scbu ON sh.unit = scbu.id  \n" +
                            "where a.id =" + vo.getId();
                    List<BacklogVo> backlogVo = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(BacklogVo.class));
                    if (null != backlogVo && backlogVo.size() > 0) {
                        BacklogVo backlogVo1 = backlogVo.get(0);
                        vo.setHouseInfo(backlogVo1.getResidenceCommunityName() + "-" +
                                backlogVo1.getBuildingNumName() + "-" + backlogVo1.getUnitName() + "-" + backlogVo1.getRoomnumber());// 房屋信息
                    }
                }


                vo.setBillId(billId);// 账单ID
                vo.setBillType(billType);// 账单类型  1 .公租房 租金押金  2. 公租房其他费用 3.房产 租金押金 4.房产其他费用

            }
            apiData.setData(list);
            apiData.setTotal(total);
            apiData.setPendingTotal(pendingTotal);
            apiData.setLaunchTotal(launchTotal);
            apiData.setParticipateTotal(participateTotal);
            apiData.setDoneTotal(doneTotal);
            resultBean.setResultData(apiData);
        } catch (Exception e) {
            log.error("BacklogService backlogList Exception = {}" + e.getMessage(), e);
            resultBean.setCode("10001");
            resultBean.setMsg("10001");
        }
        resultBean.setResultData(apiData);
        return resultBean;
    }

    public ResultBean<BacklogItemApiData<BacklogListVO>> backlogHouseList(String accessToken, Integer status,
                                                                          Integer pageNumber, Integer pageSize, String houseId, Boolean result) {
        ResultBean<BacklogItemApiData<BacklogListVO>> resultBean = new ResultBean<>();
        resultBean.setCode("10000");
        resultBean.setMsg("10000");
        BacklogItemApiData<BacklogListVO> apiData = new BacklogItemApiData<>();
        resultBean.setResultData(apiData);
        try {
            if (status == null) {
                return ResultBean.failedResultWithMsg("状态id为空");
            }

            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            String userId = tokenRedisVo.getId();
            Integer flag = tokenRedisVo.getFlag();
            StringBuilder userSql = new StringBuilder();
            StringBuilder Sql = new StringBuilder();
            List<Object> userArgs = new ArrayList<>();
            List<Object> args = new ArrayList<>();
            userSql.append(" WHERE b.match_user_id = ? ");
            userArgs.add(userId);
            // if (houseId != null) {
            //     userSql.append(" and b.house_id = ? ");
            //     userArgs.add(houseId);
            // }

            // bug 2424
            // 优化查询出当前人员所有房子的消息（之前是只能看到对应房子的消息）
            if (flag != 1) {
                List<String> houseIdList = communityService.getHouseIdList(userId);
                if (CollectionUtil.isNotEmpty(houseIdList)) {
                    StringBuilder houseIds = new StringBuilder("");
                    for (String hId : houseIdList) {
                        houseIds.append("'" + hId + "'").append(",");
                    }
                    String houseIdsStr = houseIds.toString().substring(0, houseIds.toString().lastIndexOf(","));
                    userSql.append(" and b.house_id IN (  " + houseIdsStr + " ) ");
                }
            }


            StringBuilder where = new StringBuilder();
            if (result) {
                where.append(" and b.type in(60,61)");
            }
            // 全部待办事项总记录数
            Long total = jdbcTemplate.queryForObject(BACKLOG_COUNT + userSql + where, userArgs.toArray(), Long.class);
            log.info(BACKLOG_COUNT + userSql + where, userArgs.toArray());
            if (total == 0) {
                return resultBean;
            }
            // 待我处理的总数
            Long pendingTotal = jdbcTemplate.queryForObject(BACKLOG_COUNT + userSql + where + " and b.handle_status = 0", userArgs.toArray(), Long.class);
            // 我发起的总数
            Long launchTotal = jdbcTemplate.queryForObject(BACKLOG_COUNT + userSql + where + " and b.operator_id ='" + userId + "'", userArgs.toArray(), Long.class);
            // 我参与的总数
            Long participateTotal = jdbcTemplate.queryForObject(BACKLOG_COUNT + userSql + where + " and b.handle_status = 2", userArgs.toArray(), Long.class);
            // 已完成总数
            Long doneTotal = jdbcTemplate.queryForObject(BACKLOG_COUNT + userSql + where + " and b.handle_status = 1", userArgs.toArray(), Long.class);

            if (status == 1) {// 待我处理的
                where.append(" and b.handle_status = ?");
                userArgs.add(0);
            } else if (status == 2) {// 我发起的
                where.append(" and b.operator_id = ?");
                userArgs.add(userId);
            } else if (status == 3) {// 我参与的
                where.append(" and b.handle_status = ?");
                userArgs.add(2);
            } else if (status == 4) {// 已完成的
                where.append(" and b.handle_status = ?");
                userArgs.add(1);
            }
            if (flag == 1) {
                where.append(" and b.type != 50");
            }
            userArgs.add(pageSize);
            userArgs.add(pageNumber * pageSize);
            args.add(pageSize);
            args.add(pageNumber * pageSize);
            // 待办事项集合
            List<BacklogListVO> list = new ArrayList<>();
            // 判断是否是首页请求还是列表请求
            if (pageSize > 4) {
                List<BacklogItem> backlogItems = jdbcTemplate.query(BACKLOG_COLUM + userSql + where + BACKLOG_ORDER + SQL_PAGE,
                        new BeanPropertyRowMapper<>(BacklogItem.class), userArgs.toArray());
                list = backlogItems.stream().map(backlogItem -> {
                    BacklogListVO vo = new BacklogListVO();
                    vo.setId(backlogItem.getId());
                    vo.setHouseId(backlogItem.getHouseId());
                    vo.setOrgId(backlogItem.getOrgId());
                    Integer type = backlogItem.getType();
                    vo.setType(type);
                    vo.setTitle(backlogItem.getTitle());
                    vo.setContent(backlogItem.getContent());
                    vo.setBusinessStatus(backlogItem.getBusinessStatus());
                    vo.setHandleStatus(backlogItem.getHandleStatus());
                    Date createTime = backlogItem.getCreateTime();
                    vo.setCreateTime(createTime == null ? "" : DateUtils.format(createTime, DateUtils.FORMAT_DATETIME_14));
                    vo.setApplyType(backlogItem.getApplyType());
                    vo.setShortUrl(backlogItem.getShortUrl());

                    // 申请人
                    if (type == BacklogItemTypeEnum.LOCK_BIND.getValue() || type == BacklogItemTypeEnum.ELIGIBLE_APPROVE.getValue()) {
                        vo.setApplyUserId(backlogItem.getOperatorId());
                    } else {
                        vo.setApplyUserId(backlogItem.getMatchUserId());
                    }
                    // 申请单位
                    if (type == BacklogItemTypeEnum.HOUSE_SAVE.getValue()) {
                        vo.setApplyUser(userService.findUserEnterpriseName(backlogItem.getOperatorId()));
                    }

                    return vo;
                }).collect(Collectors.toList());
            } else {
                // 如果有未读的就先返回未读的
                if (pendingTotal > 0) {
                    where.append(" and b.handle_status = 0");
                    List<BacklogItem> backlogItems = jdbcTemplate.query(BACKLOG_COLUM + userSql + where + BACKLOG_ORDER + SQL_PAGE,
                            new BeanPropertyRowMapper<>(BacklogItem.class), userArgs.toArray());
                    log.info(BACKLOG_COLUM + userSql + where + BACKLOG_ORDER + SQL_PAGE+ userArgs.toArray());
                    list = backlogItems.stream().map(backlogItem -> {
                        BacklogListVO vo = new BacklogListVO();
                        vo.setId(backlogItem.getId());
                        vo.setHouseId(backlogItem.getHouseId());
                        vo.setOrgId(backlogItem.getOrgId());
                        Integer type = backlogItem.getType();
                        vo.setType(type);
                        vo.setTitle(backlogItem.getTitle());
                        vo.setContent(backlogItem.getContent());
                        vo.setBusinessStatus(backlogItem.getBusinessStatus());
                        vo.setHandleStatus(backlogItem.getHandleStatus());
                        Date createTime = backlogItem.getCreateTime();
                        vo.setCreateTime(createTime == null ? "" : DateUtils.format(createTime, DateUtils.FORMAT_DATETIME_14));
                        vo.setApplyType(backlogItem.getApplyType());
                        vo.setShortUrl(backlogItem.getShortUrl());
                        vo.setUserName(null);
                        vo.setOperatorName(null);
                        vo.setOrgName(null);
                        // 申请人
                        if (type == BacklogItemTypeEnum.LOCK_BIND.getValue() || type == BacklogItemTypeEnum.ELIGIBLE_APPROVE.getValue()) {
                            vo.setApplyUserId(backlogItem.getOperatorId());
                        } else {
                            vo.setApplyUserId(backlogItem.getMatchUserId());
                        }
                        // 申请单位
                        if (type == BacklogItemTypeEnum.HOUSE_SAVE.getValue()) {
                            vo.setApplyUser(userService.findUserEnterpriseName(backlogItem.getOperatorId()));
                        }

                        return vo;
                    }).collect(Collectors.toList());
                } else {
                    List<BacklogItem> backlogItems = jdbcTemplate.query(BACKLOG_COLUM + userSql + where + BACKLOG_ORDER + SQL_PAGE,
                            new BeanPropertyRowMapper<>(BacklogItem.class), userArgs.toArray());
                    // List<BacklogListVO> backlogListVOS = jdbcTemplate.query(Sql +SQL_PAGE,
                    //         new BeanPropertyRowMapper<>(BacklogListVO.class), args.toArray());
                    list = backlogItems.stream().map(backlogItem -> {
                        BacklogListVO vo = new BacklogListVO();
                        vo.setId(backlogItem.getId());
                        vo.setHouseId(backlogItem.getHouseId());
                        vo.setOrgId(backlogItem.getOrgId());
                        Integer type = backlogItem.getType();
                        vo.setType(type);
                        vo.setTitle(backlogItem.getTitle());
                        vo.setContent(backlogItem.getContent());
                        vo.setBusinessStatus(backlogItem.getBusinessStatus());
                        vo.setHandleStatus(backlogItem.getHandleStatus());
                        Date createTime = backlogItem.getCreateTime();
                        vo.setCreateTime(createTime == null ? "" : DateUtils.format(createTime, DateUtils.FORMAT_DATETIME_14));
                        vo.setApplyType(backlogItem.getApplyType());
                        vo.setShortUrl(backlogItem.getShortUrl());

                        // 申请人
                        if (type == BacklogItemTypeEnum.LOCK_BIND.getValue() || type == BacklogItemTypeEnum.ELIGIBLE_APPROVE.getValue()) {
                            vo.setApplyUserId(backlogItem.getOperatorId());
                        } else {
                            vo.setApplyUserId(backlogItem.getMatchUserId());
                        }
                        // 申请单位
                        if (type == BacklogItemTypeEnum.HOUSE_SAVE.getValue()) {
                            vo.setApplyUser(userService.findUserEnterpriseName(backlogItem.getOperatorId()));
                        }

                        return vo;
                    }).collect(Collectors.toList());
                }
            }


            // 查询申请人名称
            List<String> ids = list.stream().filter(vo -> StringUtils.isNotBlank(vo.getApplyUserId())).map(BacklogListVO::getApplyUserId).distinct().collect(Collectors.toList());
            if (!ids.isEmpty()) {
                List<AppUser> appUsers = appUserRepository.findByIdOrEnterpriseIn(ids, ids);
                List<User> users = userRepository.findByIdIn(ids);
                for (BacklogListVO vo : list) {
                    String applyUserId = vo.getApplyUserId();
                    if (StringUtils.isNotBlank(applyUserId)) {
                        for (AppUser appUser : appUsers) {
                            if (applyUserId.equals(appUser.getId()) || applyUserId.equals(appUser.getEnterpriseUserId())) {
                                vo.setApplyUser(appUser.getName());
                                break;
                            }
                        }
                        if (StringUtils.isBlank(vo.getApplyUser())) {
                            for (User u : users) {
                                if (applyUserId.equals(u.getId())) {
                                    vo.setApplyUser(u.getName());
                                    break;
                                }
                            }
                        }
                    }
                }
            }

            // 如果有配租待办事项，查询待配租小区id
            List<Long> backlogItemIds = list.stream().filter(v -> v.getType() != null && v.getType() == 4).map(m -> m.getId()).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(backlogItemIds)) {
                List<BacklogItemRent> backlogItemRentList = backlogItemRentRepository.findByBacklogItemIdIn(backlogItemIds);
                if (!backlogItemRentList.isEmpty()) {
                    for (BacklogListVO vo : list) {
                        if (vo.getType() != null && vo.getType() == 4) {
                            for (BacklogItemRent backlogItemRent : backlogItemRentList) {
                                if (backlogItemRent.getBacklogItemId() != null && backlogItemRent.getBacklogItemId().longValue() == vo.getId().longValue()) {
                                    vo.setResidenceCommunityId(backlogItemRent.getResidenceCommunityId());
                                }
                            }
                        }
                    }
                }
            }
            // 获得账单ID ，和类型
            for (BacklogListVO vo : list) {
                String billId = null;
                Integer billType = null; // 账单类型  1 .公租房 租金押金  2. 公租房其他费用 3.房产 租金押金 4.房产其他费用
                /**
                 *   2-智能锁冻结(公租房 租金/押金)
                 *   18- 公租房 (合同)租金押金
                 *    36 公租房(合同) 租金/押金账单
                 */
                String sql = null;
                if (vo.getType() == 2) {
                    sql = " select \n" +
                            "b.bill_id as billId ,\n" +
                            "sc.name AS residenceCommunityName,\n" +
                            "scb.name AS buildingNumName,\n" +
                            "scbu.name AS unitName,\n" +
                            "sh.room_number AS roomnumber ,\n" +
                            "c.payment_time as paymentTime,\n" +
                            "c.cost as money\n" +
                            "from  saas_backlog_item a\n" +
                            "LEFT JOIN saas_backlog_item_lock b on b.backlog_item_id = a.id \n" +
                            "LEFT JOIN saas_rent_bill c on c.id = b.bill_id\n" +
                            " LEFT JOIN saas_house sh    ON sh.id = c.house_id\n" +
                            "LEFT JOIN saas_community sc ON sh.residence_community_id = sc.id\n" +
                            "LEFT JOIN saas_community_build scb ON sh.building_num = scb.id \n" +
                            "LEFT JOIN saas_community_build_unit scbu ON sh.unit = scbu.id \n" +
                            "where a.id= " + vo.getId();
                    List<BacklogVo> backlogVo = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(BacklogVo.class));
                    if (null != backlogVo && backlogVo.size() > 0) {
                        BacklogVo backlogVo1 = backlogVo.get(0);
                        billId = backlogVo1.getBillId();
                        vo.setHouseInfo(backlogVo1.getResidenceCommunityName() + "-" +
                                backlogVo1.getBuildingNumName() + "-" + backlogVo1.getUnitName() + "-" + backlogVo1.getRoomnumber());// 房屋信息
                        vo.setMoney(fenToYuan(backlogVo1.getMoney()));// 金额
                        vo.setPaymentTime(backlogVo1.getPaymentTime());// 缴费时间


                    }
                    billType = 1;
                }

                if (vo.getType() == 18 || vo.getType() == 36) {
                    sql = "select IFNULL(b.rent_bill_id,b.deposit_bill_id) as billId ,\n" +
                            "sc.name AS residenceCommunityName,\n" +
                            "scb.name AS buildingNumName,\n" +
                            "scbu.name AS unitName,\n" +
                            "sh.room_number AS roomnumber ,\n" +
                            "c.payment_time as paymentTime,\n" +
                            "c.cost as money\n" +
                            "from  saas_backlog_item a\n" +
                            "LEFT JOIN saas_backlog_item_contract_bill b on b.backlog_item_id = a.id\n" +
                            "LEFT JOIN saas_rent_bill c on c.id = b.rent_bill_id or  c.id = b.deposit_bill_id\n" +
                            " LEFT JOIN saas_house sh    ON sh.id = c.house_id\n" +
                            "LEFT JOIN saas_community sc ON sh.residence_community_id = sc.id\n" +
                            "LEFT JOIN saas_community_build scb ON sh.building_num = scb.id \n" +
                            "LEFT JOIN saas_community_build_unit scbu ON sh.unit = scbu.id \n" +
                            "where a.id= " + vo.getId();

                    List<BacklogVo> backlogVo = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(BacklogVo.class));
                    if (null != backlogVo && backlogVo.size() > 0) {
                        BacklogVo backlogVo1 = backlogVo.get(0);
                        billId = backlogVo1.getBillId();
                        vo.setHouseInfo(backlogVo1.getResidenceCommunityName() + "-" +
                                backlogVo1.getBuildingNumName() + "-" + backlogVo1.getUnitName() + "-" + backlogVo1.getRoomnumber());// 房屋信息
                        vo.setMoney(fenToYuan(backlogVo1.getMoney()));// 金额
                        vo.setPaymentTime(backlogVo1.getPaymentTime());// 缴费时间
                    }
                    billType = 1;
                }

                // 获得公租房其他账单 saas_backlog_item_house_other_bill
                if (vo.getType() == 37 || vo.getType() == 42) {
                    sql = "select b.bill_id as billId ,\n" +
                            "sc.name AS residenceCommunityName,\n" +
                            "scb.name AS buildingNumName,\n" +
                            "scbu.name AS unitName,\n" +
                            "sh.room_number AS roomnumber ,\n" +
                            "c.payment_time as paymentTime,\n" +
                            "c.cost as money\n" +
                            "from  saas_backlog_item a\n" +
                            "LEFT JOIN saas_backlog_item_house_other_bill b on b.backlog_item_id = a.id \n" +
                            "LEFT JOIN saas_expense_bill c on c.id = b.bill_id \n" +
                            " LEFT JOIN saas_house sh   ON sh.id = c.house_id\n" +
                            "LEFT JOIN saas_community sc ON sh.residence_community_id = sc.id\n" +
                            "LEFT JOIN saas_community_build scb ON sh.building_num = scb.id \n" +
                            "LEFT JOIN saas_community_build_unit scbu ON sh.unit = scbu.id \n" +
                            "  where a.id =" + vo.getId();

                    List<BacklogVo> backlogVo = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(BacklogVo.class));
                    if (null != backlogVo && backlogVo.size() > 0) {
                        BacklogVo backlogVo1 = backlogVo.get(0);
                        billId = backlogVo1.getBillId();
                        vo.setHouseInfo(backlogVo1.getResidenceCommunityName() + "-" +
                                backlogVo1.getBuildingNumName() + "-" + backlogVo1.getUnitName() + "-" + backlogVo1.getRoomnumber());// 房屋信息
                        vo.setMoney(fenToYuan(backlogVo1.getMoney()));// 金额
                        vo.setPaymentTime(backlogVo1.getPaymentTime());// 缴费时间

                    }
                    billType = 2;
                }


                // 获得非公租房（房产） / 租金押金账单 saas_backlog_item_property_rent_bill
                if (vo.getType() == 38) {
                    sql = "select IFNULL(b.rent_bill_id,b.deposit_bill_id) as billId ,\n" +
                            "sc.name AS residenceCommunityName,\n" +
                            "scb.name AS buildingNumName,\n" +
                            "scbu.name AS unitName,\n" +
                            "sh.room_number AS roomnumber ,\n" +
                            "c.payment_time as paymentTime,\n" +
                            "c.cost as money\n" +
                            "from  saas_backlog_item a\n" +
                            "LEFT JOIN saas_backlog_item_property_rent_bill b on b.backlog_item_id = a.id \n" +
                            "LEFT JOIN saas_estate_rent_bill c on c.id = b.rent_bill_id or  c.id = b.deposit_bill_id\n" +
                            "LEFT JOIN saas_house sh    ON sh.id = c.house_id\n" +
                            "LEFT JOIN saas_community sc ON sh.residence_community_id = sc.id\n" +
                            "LEFT JOIN saas_community_build scb ON sh.building_num = scb.id \n" +
                            "LEFT JOIN saas_community_build_unit scbu ON sh.unit = scbu.id \n" +
                            "where a.id=" + vo.getId();

                    List<BacklogVo> backlogVo = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(BacklogVo.class));
                    if (null != backlogVo && backlogVo.size() > 0) {
                        BacklogVo backlogVo1 = backlogVo.get(0);
                        billId = backlogVo1.getBillId();
                        vo.setHouseInfo(backlogVo1.getResidenceCommunityName() + "-" +
                                backlogVo1.getBuildingNumName() + "-" + backlogVo1.getUnitName() + "-" + backlogVo1.getRoomnumber());// 房屋信息
                        vo.setMoney(fenToYuan(backlogVo1.getMoney()));// 金额
                        vo.setPaymentTime(backlogVo1.getPaymentTime());// 缴费时间
                    }
                    billType = 3;
                }

                // 获得非公租房（房产）其他账单 saas_backlog_item_property_rent_bill
                if (vo.getType() == 39 || vo.getType() == 41) {
                    sql = "select b.bill_id as billId ,\n" +
                            "sc.name AS residenceCommunityName,\n" +
                            "scb.name AS buildingNumName,\n" +
                            "scbu.name AS unitName,\n" +
                            "sh.room_number AS roomnumber ,\n" +
                            "c.payment_time as paymentTime,\n" +
                            "c.cost as money\n" +
                            "from  saas_backlog_item a\n" +
                            "LEFT JOIN saas_backlog_item_property_other_bill b on b.backlog_item_id = a.id \n" +
                            "LEFT JOIN saas_estate_expense_bill c on c.id = b.bill_id \n" +
                            "LEFT JOIN saas_house sh    ON sh.id = c.house_id\n" +
                            "LEFT JOIN saas_community sc ON sh.residence_community_id = sc.id\n" +
                            "LEFT JOIN saas_community_build scb ON sh.building_num = scb.id \n" +
                            "LEFT JOIN saas_community_build_unit scbu ON sh.unit = scbu.id \n" +
                            "where a.id=" + vo.getId();

                    List<BacklogVo> backlogVo = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(BacklogVo.class));
                    if (null != backlogVo && backlogVo.size() > 0) {
                        BacklogVo backlogVo1 = backlogVo.get(0);
                        billId = backlogVo1.getBillId();
                        vo.setHouseInfo(backlogVo1.getResidenceCommunityName() + "-" +
                                backlogVo1.getBuildingNumName() + "-" + backlogVo1.getUnitName() + "-" + backlogVo1.getRoomnumber());// 房屋信息
                        vo.setMoney(fenToYuan(backlogVo1.getMoney()));// 金额
                        vo.setPaymentTime(backlogVo1.getPaymentTime());// 缴费时间
                    }
                    billType = 4;
                }

                // 催缴待办事项
                if (vo.getType() == 40) {
                    sql = "select * from  (select a.id ,IFNULL(b.rent_bill_id,b.deposit_bill_id) as billId, 3 AS billType ,if (c.charge_type= 1 ,8,9) as chargeType from  saas_backlog_item a \n" +
                            "LEFT JOIN saas_backlog_item_property_rent_bill b on b.backlog_item_id =a.id \n" +
                            "LEFT JOIN saas_estate_rent_bill c on c.id =b.rent_bill_id or  c.id =b.deposit_bill_id \n" +
                            "UNION  \n" +
                            "select a.id ,b.bill_id as billId , 4 AS billType ,c.charge_type as chargeType from  saas_backlog_item a \n" +
                            "LEFT JOIN saas_backlog_item_bill b on b.backlog_item_id =a.id \n" +
                            "LEFT JOIN saas_estate_expense_bill c on c.id =b.bill_id\n" +
                            ") t1 where t1.id=" + vo.getId() + " and billId is not null ";

                    List<BacklogListVO> backlogListVOS = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(BacklogListVO.class));
                    if (null != backlogListVOS && backlogListVOS.size() > 0) {
                        billId = backlogListVOS.get(0).getBillId();
                        billType = backlogListVOS.get(0).getBillType();
                        vo.setChargeType(backlogListVOS.get(0).getChargeType());
                    }
                }
                // 成员变更 添加字段
                if (vo.getType() == 30 || vo.getType() == 31) {
                    sql = " select sc.name AS residenceCommunityName,\n" +//
                            "scb.name AS buildingNumName,\n" +
                            "scbu.name AS unitName,\n" +
                            "sh.room_number AS roomnumber ,\n" +
                            "c.name as userName,\n" +
                            "c.mobile,\n" +
                            "c.type as userType\n" +
                            "from saas_backlog_item a\n" +
                            "LEFT JOIN saas_backlog_item_house_user b on b.backlog_item_id = a.id \n" +
                            "LEFT JOIN saas_community_house_user c on c.id =  b.house_user_id\n" +
                            "LEFT JOIN saas_house sh       ON sh.id = c.community_house_id\n" +
                            "LEFT JOIN saas_community sc ON sh.residence_community_id = sc.id\n" +
                            "LEFT JOIN saas_community_build scb ON sh.building_num = scb.id LEFT JOIN saas_community_build_unit scbu ON sh.unit = scbu.id \n" +
                            "where a.id=" + vo.getId();
                    List<BacklogVo> backlogVo = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(BacklogVo.class));
                    if (null != backlogVo && backlogVo.size() > 0) {
                        BacklogVo backlogVo1 = backlogVo.get(0);
                        vo.setMobile(backlogVo1.getMobile());// 手机号
                        vo.setUserName(backlogVo1.getUserName());// 姓名
                        vo.setUserType(backlogVo1.getUserType());// 人员类型
                        vo.setHouseInfo(backlogVo1.getResidenceCommunityName() + "-" +
                                backlogVo1.getBuildingNumName() + "-" + backlogVo1.getUnitName() + "-" + backlogVo1.getRoomnumber());// 房屋信息
                    }

                }
                // 智能锁冻结
                if (vo.getType() == 32 || vo.getType() == 33 || vo.getType() == 34 || vo.getType() == 35) {
                    sql = "select sc.name AS residenceCommunityName, \n" +
                            "scb.name AS buildingNumName, \n" +
                            "scbu.name AS unitName, \n" +
                            "sh.room_number AS roomnumber \n" +
                            "from saas_backlog_item a \n" +
                            "LEFT JOIN saas_house sh       ON sh.id = a.house_id \n" +
                            "LEFT JOIN saas_community sc ON sh.residence_community_id = sc.id \n" +
                            "LEFT JOIN saas_community_build scb ON sh.building_num = scb.id LEFT JOIN saas_community_build_unit scbu ON sh.unit = scbu.id  \n" +
                            "where a.id =" + vo.getId();
                    List<BacklogVo> backlogVo = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(BacklogVo.class));
                    if (null != backlogVo && backlogVo.size() > 0) {
                        BacklogVo backlogVo1 = backlogVo.get(0);
                        vo.setHouseInfo(backlogVo1.getResidenceCommunityName() + "-" +
                                backlogVo1.getBuildingNumName() + "-" + backlogVo1.getUnitName() + "-" + backlogVo1.getRoomnumber());// 房屋信息
                    }
                }


                vo.setBillId(billId);// 账单ID
                vo.setBillType(billType);// 账单类型  1 .公租房 租金押金  2. 公租房其他费用 3.房产 租金押金 4.房产其他费用

            }
            apiData.setData(list);
            apiData.setTotal(total);
            apiData.setPendingTotal(pendingTotal);
            apiData.setLaunchTotal(launchTotal);
            apiData.setParticipateTotal(participateTotal);
            apiData.setDoneTotal(doneTotal);
            resultBean.setResultData(apiData);
        } catch (Exception e) {
            log.error("BacklogService backlogList Exception = {}" + e.getMessage(), e);
            resultBean.setCode("10001");
            resultBean.setMsg("10001");
        }
        resultBean.setResultData(apiData);
        return resultBean;
    }


    public ResultBean<HouseBindDetailVO> houseBindDetail(String accessToken, Long id) {
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            String userId = tokenRedisVo.getId();

            if (id == null) {
                return ResultBean.failedResultOfParamWithMsg("待办事项id为空");
            }

            Optional<BacklogItem> itemOptional = backlogItemRepository.findById(id);
            if (!itemOptional.isPresent()) {
                return ResultBean.failedResultWithMsg("待办事项不存在");
            }
            BacklogItem backlogItem = itemOptional.get();
            String operatorId = backlogItem.getOperatorId();

            String houseId = backlogItem.getHouseId();
            Optional<House> houseOptional = houseRepository.findById(houseId);
            if (!houseOptional.isPresent()) {
                return ResultBean.failedResultWithMsg("公租房不存在");
            }
            House house = houseOptional.get();

            String userName = "";
            AppUser appUser = appUserRepository.findByIdOrEnterpriseUserId(operatorId, operatorId);
            if (appUser != null) {
                userName = appUser.getName();
            } else {
                User user = userRepository.findUserById(operatorId);
                if (user == null) {
                    log.info("BacklogService houseBindDetail ----> 申请人不存在, operatorId = {}", operatorId);
                    return ResultBean.failedResultWithMsg("申请人不存在");
                }
                userName = user.getName();
            }

            HouseBindDetailVO vo = new HouseBindDetailVO();
            vo.setApplyUser(userName);// 申请人
            vo.setApplyDept(userService.findUserEnterpriseName(operatorId));// 申请人机构
            Long orgId = backlogItem.getOrgId();
            Long houseSum = jdbcTemplate.queryForObject("SELECT COUNT(1) FROM `saas_house` h WHERE h.`org_id` = ?", new Object[]{orgId}, Long.class);
            vo.setHouseSum(houseSum);
            Date createTime = backlogItem.getCreateTime();
            Date handlerTime = backlogItem.getHandlerTime();
            vo.setCreateTime(createTime == null ? "" : DateUtils.format(createTime, DateUtils.FORMAT_DATETIME_14));
            vo.setStatus(backlogItem.getHandleStatus());
            vo.setHandlerTime(handlerTime == null ? "" : DateUtils.format(handlerTime, DateUtils.FORMAT_DATETIME_14));
            vo.setApproveUser(tokenRedisVo.getName());// 审批人
            vo.setApproveDept(userService.findUserEnterpriseName(userId));// 审批人机构
            vo.setAuditStatus(backlogItem.getAuditStatus());

            return ResultBean.successfulResult(vo);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    /**
     * 审批公租房绑定,实现公租房的审批操作
     *
     * @param accessToken 权限鉴定
     * @param id          待办事项id
     * @param type        1通过 2不通过
     * @return
     */
    public ResultBean<Object> approveHouseBind(String accessToken, Long id, Integer type) {
        try {
            // 判断待办事项id为是否空
            if (id == null) {
                return ResultBean.failedResultOfParamWithMsg("待办事项id为空");
            }
            // 判断审批类型是否为空：1通过，2不通过
            if (type == null) {
                return ResultBean.failedResultOfParamWithMsg("类型为空");
            }
            // 根据待办事项id查询数据
            Optional<BacklogItem> itemOptional = backlogItemRepository.findById(id);
            if (!itemOptional.isPresent()) {
                return ResultBean.failedResultWithMsg("待办事项不存在");
            }
            // 获取需要待办的事项
            BacklogItem backlogItem = itemOptional.get();
            // 获取公租房ID
            String houseId = backlogItem.getHouseId();
            // 获取公租房数据
            Optional<House> houseOptional = houseRepository.findById(houseId);
            if (!houseOptional.isPresent()) {
                return ResultBean.failedResultWithMsg("公租房不存在");
            }
            House house = houseOptional.get();

            // 修改房源审核状态
            if (type == 1) {// 通过
                house.setAuditStatus(HouseAuditStatusEnum.AUDIT.getValue());
                // 如果该房屋有轮候配租记录，修改成可配租状态
                List<WaitingRentRecord> waitingRentRecords = waitingRentRecordRepository.
                        findByOrgIdAndResidenceCommunityIdAndStatus(house.getOrgId(), house.getResidenceCommunityId(), 0);
                if (!waitingRentRecords.isEmpty()) {
                    house.setMatchStatus(1);
                }
            } else if (type == 2) {// 不通过
                house.setAuditStatus(HouseAuditStatusEnum.NO_PASS.getValue());
            }
            houseRepository.save(house);

            // 更新待办事项
            backlogItem.setBusinessStatus("已审批");
            backlogItem.setHandleStatus(1);// 1已读/已处理
            backlogItem.setHandlerTime(new Date());
            backlogItem.setAuditStatus(type);
            backlogItemRepository.save(backlogItem);
            // 将修改的结果返回给前端页面
            return ResultBean.successfulResult(null);
        } catch (Exception e) {
            // 打印报错信息
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<ApiData<HouseVO>> findBindData(String accessToken, Long id, Integer pageNumber,
                                                     Integer pageSize) {
        ResultBean<ApiData<HouseVO>> resultBean = new ResultBean<>();
        resultBean.setCode("10000");
        resultBean.setMsg("10000");
        ApiData<HouseVO> apiData = new ApiData<>();
        resultBean.setResultData(apiData);
        try {
            if (id == null) {
                return ResultBean.failedResultOfParamWithMsg("待办事项id为空");
            }

            Optional<BacklogItem> itemOptional = backlogItemRepository.findById(id);
            if (!itemOptional.isPresent()) {
                return ResultBean.failedResultWithMsg("待办事项不存在");
            }
            BacklogItem backlogItem = itemOptional.get();
            String houseId = backlogItem.getHouseId();

            StringBuilder where = new StringBuilder();
            List<Object> args = new ArrayList<>();
            where.append(" where h.id = ?");
            args.add(houseId);

            // 总数
            Long total = jdbcTemplate.queryForObject("SELECT COUNT(1) FROM saas_house h" + where, args.toArray(),
                    Long.class);
            if (total == 0) {
                return resultBean;
            }

            args.add(pageSize);
            args.add(pageNumber * pageSize);
            List<HouseVO> houseList = jdbcTemplate.query("SELECT * FROM saas_house h" + where + HOUDE_ORDER + SQL_PAGE,
                    new BeanPropertyRowMapper<>(HouseVO.class), args.toArray());

            // 查询区域名称
            List<Long> ids = new ArrayList<>();
            List<Long> provinceIds = houseList.stream().filter(vo -> vo.getProvinceId() != null)
                    .map(HouseVO::getProvinceId).distinct().collect(Collectors.toList());
            List<Long> cityIds = houseList.stream().filter(vo -> vo.getCityId() != null).map(HouseVO::getCityId)
                    .distinct().collect(Collectors.toList());
            List<Long> districtIds = houseList.stream().filter(vo -> vo.getDistrictId() != null)
                    .map(HouseVO::getDistrictId).distinct().collect(Collectors.toList());
            List<Long> streetIds = houseList.stream().filter(vo -> vo.getStreetId() != null).map(HouseVO::getStreetId)
                    .distinct().collect(Collectors.toList());
            List<Long> communityIds = houseList.stream().filter(vo -> vo.getCommunityId() != null)
                    .map(HouseVO::getCommunityId).distinct().collect(Collectors.toList());
            ids.addAll(provinceIds);
            ids.addAll(cityIds);
            ids.addAll(districtIds);
            ids.addAll(streetIds);
            ids.addAll(communityIds);
            if (!ids.isEmpty()) {
                Map<Long, String> map = areaRepository.findByIdIn(ids).stream()
                        .collect(Collectors.toMap(Area::getId, Area::getName));
                if (!map.isEmpty()) {
                    for (HouseVO vo : houseList) {
                        vo.setProvince(map.get(vo.getProvinceId()));
                        vo.setCity(map.get(vo.getCityId()));
                        vo.setDistrict(map.get(vo.getDistrictId()));
                        vo.setStreet(map.get(vo.getStreetId()));
                        vo.setCommunity(map.get(vo.getCommunityId()));
                    }
                }
            }
            // 查询小区名称
            List<String> rcIds = houseList.stream().filter(vo -> vo.getResidenceCommunityId() != null)
                    .map(HouseVO::getResidenceCommunityId).distinct().collect(Collectors.toList());
            if (!rcIds.isEmpty()) {
                Map<String, String> map = communityRepository.findByIdIn(rcIds).stream()
                        .collect(Collectors.toMap(Community::getId, Community::getName));
                if (!map.isEmpty()) {
                    houseList.forEach(vo -> vo.setResidenceCommunityName(map.get(vo.getResidenceCommunityId())));
                }
            }
            // 查询楼栋名称
            List<Long> buildingIds = houseList.stream().filter(vo -> vo.getBuildingNum() != null)
                    .map(HouseVO::getBuildingNum).distinct().collect(Collectors.toList());
            if (!buildingIds.isEmpty()) {
                Map<Long, String> map = communityBuildRepository.findByIdIn(buildingIds).stream()
                        .collect(Collectors.toMap(CommunityBuild::getId, CommunityBuild::getName));
                if (!map.isEmpty()) {
                    houseList.forEach(vo -> vo.setBuildingNumName(map.get(vo.getBuildingNum())));
                }
            }
            // 查询单元名称
            List<Long> unitIds = houseList.stream().filter(vo -> vo.getUnit() != null).map(HouseVO::getUnit).distinct()
                    .collect(Collectors.toList());
            if (!unitIds.isEmpty()) {
                Map<Long, String> map = communityBuildUnitRepository.findByIdIn(unitIds).stream()
                        .collect(Collectors.toMap(CommunityBuildUnit::getId, CommunityBuildUnit::getName));
                if (!map.isEmpty()) {
                    houseList.forEach(vo -> vo.setUnitName(map.get(vo.getUnit())));
                }
            }

            apiData.setData(houseList);
            apiData.setTotal(total);
            resultBean.setResultData(apiData);

            return ResultBean.successfulResult(apiData);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    /**
     * 待办事项app支付
     *
     * @param accessToken
     * @param vo
     * @return
     */
    public ResultBean<Map<String, Object>> payment(@RequestHeader String accessToken,
                                                   @RequestBody BacklogPaymentVO vo) {

        log.info("BacklogService payment vo={}", vo.toString());
        try {
            if (vo.getId() == null || vo.getPaymentMode() == null || vo.getPaymentType() == null) {
                return ResultBean.failedResultOfParamWithMsg("参数错误");
            }

            if (!BacklogItemTypeEnum.operate(vo.getBoacklogType())) {
                return ResultBean.failedResultOfParamWithMsg("参数错误");
            }

            if (vo.getBoacklogType() != 2) {
                return ResultBean.failedResultOfParamWithMsg("暂不支持其它类型支付");
            }

            if (!PaymentTypeEnum.operate(vo.getPaymentType()) || !PaymentModeEnum.operate(vo.getPaymentMode())) {
                return ResultBean.failedResultOfParamWithMsg("参数错误");
            }

            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }

            String userId = tokenRedisVo.getId();
            // 操作用户企业id
            Long enterpriseId = tokenRedisVo.getEnterpriseId();
            Optional<BacklogItem> backlogOpt = backlogItemRepository.findById(vo.getId());

            if (!backlogOpt.isPresent()) {
                return ResultBean.failedResultOfParamWithMsg("参数错误");
            }

            BacklogItem item = backlogOpt.get();
            // 事项处理状态：0未读/未处理 1已读/已处理
            if (item.getHandleStatus() == 1) {
                log.warn("BacklogService payment 该事项已被处理,无需重复处理 id={},status={}", vo.getId(), item.getHandleStatus());
                return ResultBean.failedResultOfParamWithMsg("该事项已被处理,无需重复处理");
            }

            List<BacklogItemLock> backlogList = backlogItemLockRepository.findByBacklogItemId(item.getId());

            if (CollectionUtils.isEmpty(backlogList)) {
                log.warn("BacklogService payment 未找到该事项详情 id={},status={}", vo.getId());
                return ResultBean.failedResultOfParamWithMsg("未找到该事项详情,可以前去缴费管理查看支付");
            }

            List<Long> ids = backlogList.stream().map(BacklogItemLock::getBacklogItemId).collect(Collectors.toList());

            List<RentBill> rentBills = rentBillRepository.findByIdIn(ids);

            if (CollectionUtils.isEmpty(rentBills)) {
                log.warn("BacklogService payment 未找到租金费用明细 id={}", ids);
                return ResultBean.failedResultWithMsg("未找到租金费用明细,请重试");
            }

            Integer cose = 0;
            for (RentBill rentBill : rentBills) {
                if (rentBill.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                    log.warn("BacklogService payment 此租金费用已支付,无需重复支付 id={},houseId={}", rentBill.getId(),
                            rentBill.getHouseId());
                    continue;
                }
                cose += rentBill.getCost();
            }

            // 手续费比例
            String platStr = redisService.getValue("platform.commission");
            BigDecimal totalAmount = DataUtils.IntegerToBigdecimal(cose);
            Integer plat = 0;
            if (StringUtils.isNotBlank(platStr)) {
                BigDecimal platform = DataUtils.IntegerToBigdecimal(Integer.valueOf(platStr));
                BigDecimal platAmount = totalAmount.multiply(platform).setScale(2, BigDecimal.ROUND_HALF_UP);
                totalAmount = totalAmount.add(platAmount).setScale(2, BigDecimal.ROUND_HALF_UP);
                plat = DataUtils.doubleToInteger(platAmount.doubleValue());
            }

            Long orgId = item.getOrgId();
            String outTradeNo = String.valueOf(KeyWorker.nextId());

            BacklogItemRedisVo redisVo = new BacklogItemRedisVo();
            redisVo.setOrgId(orgId);
            redisVo.setPaymentMode(vo.getPaymentMode());
            redisVo.setPaymentStatus(0);
            redisVo.setPlat(plat);
            redisVo.setUserId(userId);
            redisVo.setOutTradeNo(outTradeNo);
            redisVo.setType(vo.getBoacklogType());
            redisVo.setId(vo.getId());
            redisVo.setTotalAmount(totalAmount);
            redisVo.setBusinessType(3);

            // 操作用户企业信息
            DepartmentHierarchy departmentHierarchy = departmentHierarchyService.getEnterpriseInfo(orgId);
            if (departmentHierarchy == null) {
                log.warn("BacklogService payment 未找到您当前所在机构/企业 userId={},enterpriseId={}", userId, enterpriseId);
                return ResultBean.failedResultWithMsg("企业信息错误");
            }

            if (vo.getPaymentType() == PaymentTypeEnum.WECHAT.getValue()) {
                WechatAccount account = null;
                // 根据企业设置, 获取收款方式(平台收款, 企业商户号收款)
                // 收款方式：0平台商户号收款 1企业商户号收款
                if (departmentHierarchy.getMerchantsType() == 0) {
                    // 0为平台收款商户号企业id
                    account = wechatAccountRepository.findByOrgIdAndType(0L, PaymentTypeEnum.WECHAT.getValue());
                } else {
                    // 默认使用企业账户号收款
                    account = wechatAccountRepository.findByOrgIdAndType(orgId, PaymentTypeEnum.WECHAT.getValue());
                }

                if (account == null) {
                    log.warn("BacklogService payment 未找到微信商户配置,请联系负责人orgId={}", orgId);
                    return ResultBean.failedResultWithMsg("未找到微信商户配置,请联系客服");
                }

                String appId = "";
                if(tokenRedisVo.getFlag() == 2){
                    appId =  redisService.getValue(Constant.WX_APPLET_APPID);
                }else if (tokenRedisVo.getFlag() == 3){
                    appId =  redisService.getValue(Constant.WX_APARTMENT_APPID);
                }else if (tokenRedisVo.getFlag() == 5){
                    appId = officialAccountAppId;
                }
                String attac = outTradeNo;
                String spbillCreateIp = redisService.getValue(Constant.SPBILL_CREATE_IP);
                String body = "房屋管家-租金/押金";
                cose = DataUtils.doubleToInteger(totalAmount.doubleValue());
                WxPay wxpay = new WxPay(appId, account.getMchId(), outTradeNo, attac, cose, body,
                        account.getMchApiKey(), null, payConfig.getWxNotifyUrl(), payConfig.getUnifiedApi(),
                        spbillCreateIp);
                Map<String, Object> result = new WxPayRequest(wxpay).unifiedByApp();
                if (result == null) {
                    return ResultBean.failedResultWithMsg("微信支付异常,请联系客服");
                }
                redisVo.setMchApiKey(account.getMchApiKey());
                redisVo.setMerchantId(account.getId());
                redisService.putPaymentBacklog(redisVo);
                return ResultBean.successfulResult(result);
            }

            if (vo.getPaymentType() == PaymentTypeEnum.ALI.getValue()) {
                WechatAccount account = null;
                // 收款方式：0平台商户号收款 1企业商户号收款
                if (departmentHierarchy.getMerchantsType() == 0) {
                    // 0为平台收款商户号企业id
                    account = wechatAccountRepository.findByOrgIdAndType(0L, PaymentTypeEnum.ALI.getValue());
                } else {
                    // 默认使用企业账户号收款
                    account = wechatAccountRepository.findByOrgIdAndType(orgId, PaymentTypeEnum.ALI.getValue());
                }

                if (account == null) {
                    log.warn("BacklogService payment 未找到支付宝配置,请联系负责人 orgId={}", orgId);
                    return ResultBean.failedResultWithMsg("未找到支付宝配置,请联系负责人");
                }
                String subject = "房屋管家-租金/押金";
                String passbackParams = outTradeNo;

                AliPay alipay = new AliPay(account.getMchId(), account.getPrivateKey(), account.getPublicKey(),
                        outTradeNo, totalAmount.toString(), subject, "QUICK_MSECURITY_PAY", passbackParams,
                        payConfig.getAliNotifyUrl());

                Map<String, Object> result = new AliPayRequest(alipay).appPay();

                if (result == null) {
                    return ResultBean.failedResultWithMsg("支付宝支付异常,请联系客服");
                }
                redisVo.setPublicKey(account.getPublicKey());
                redisVo.setMerchantId(account.getId());
                redisService.putPaymentBacklog(redisVo);
                return ResultBean.successfulResult(result);
            }

            return ResultBean.failedResultOfParamWithMsg("参数错误");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<PersonLockDetailVO> personLockDetail(String accessToken, Long id) {
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            String userId = tokenRedisVo.getId();

            AppUser appUser = appUserRepository.findByIdOrEnterpriseUserId(userId, userId);
            if (appUser == null) {
                return ResultBean.failedResultWithMsg("用户不存在");
            }

            if (id == null) {
                return ResultBean.failedResultOfParamWithMsg("待办事项id为空");
            }

            Optional<BacklogItem> itemOptional = backlogItemRepository.findById(id);
            if (!itemOptional.isPresent()) {
                return ResultBean.failedResultWithMsg("待办事项不存在");
            }
            BacklogItem backlogItem = itemOptional.get();

            BacklogItemPerson backlogItemPerson = backlogItemPersonRepository.findByBacklogItemId(id);
            if (backlogItemPerson == null) {
                return ResultBean.failedResultWithMsg("待办事项参数数据不存在");
            }
            Long lockId = backlogItemPerson.getLockId();

            Optional<SmartLock> lockOpt = smartLockRepository.findById(lockId);
            if (!lockOpt.isPresent()) {
                return ResultBean.failedResultWithMsg("智能锁不存在");
            }
            SmartLock smartLock = lockOpt.get();

            String operatorId = backlogItem.getOperatorId();
            AppUser user = appUserRepository.findByIdOrEnterpriseUserId(operatorId, operatorId);
            if (user == null) {
                return ResultBean.failedResultWithMsg("申请人不存在");
            }

            PersonLockDetailVO vo = new PersonLockDetailVO();
            vo.setApplyUser(user.getName());
            vo.setApplyDept(userService.findUserEnterpriseName(operatorId));// 申请人机构
            vo.setHouseInfo(smartLock.getCommunityName() + smartLock.getBuildName() + "栋" + smartLock.getUnitName() + "单元" + smartLock.getRoomNumber() + "号");
            Date createTime = backlogItem.getCreateTime();
            Date handlerTime = backlogItem.getHandlerTime();
            vo.setCreateTime(createTime == null ? "" : DateUtils.format(createTime, DateUtils.FORMAT_DATETIME_14));
            vo.setStatus(backlogItem.getHandleStatus());
            vo.setHandlerTime(handlerTime == null ? "" : DateUtils.format(handlerTime, DateUtils.FORMAT_DATETIME_14));
            if (backlogItem.getHandleStatus() == 0) {
                vo.setApproveUser(appUser.getName());
                vo.setApproveDept(userService.findUserEnterpriseName(userId));// 审批人机构
            } else {
                String auditUserId = backlogItemPerson.getAuditUserId();
                AppUser auditUser = appUserRepository.findByIdOrEnterpriseUserId(auditUserId, auditUserId);
                if (auditUser == null) {
                    return ResultBean.failedResultWithMsg("审批人不存在");
                }
                vo.setApproveUser(auditUser.getName());
                vo.setApproveDept(userService.findUserEnterpriseName(auditUserId));// 审批人机构
            }
            vo.setAuditStatus(backlogItemPerson.getAuditStatus());
            vo.setReason(backlogItemPerson.getReason());

            return ResultBean.successfulResult(vo);
        } catch (Exception e) {
            log.error("BackLogService personLockDetail Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<Object> personLockConfirm(String accessToken, Long id, Integer type, String reason) {
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            String tokenUserId = tokenRedisVo.getId();

            if (id == null) {
                return ResultBean.failedResultOfParamWithMsg("待办事项id为空");
            }
            if (type == null) {
                return ResultBean.failedResultOfParamWithMsg("审批类型为空");
            }

            Optional<BacklogItem> itemOptional = backlogItemRepository.findById(id);
            if (!itemOptional.isPresent()) {
                return ResultBean.failedResultWithMsg("待办事项不存在");
            }
            BacklogItem backlogItem = itemOptional.get();

            BacklogItemPerson backlogItemPerson = backlogItemPersonRepository.findByBacklogItemId(id);
            if (backlogItemPerson == null) {
                return ResultBean.failedResultWithMsg("待办事项参数数据不存在");
            }
            Long lockId = backlogItemPerson.getLockId();
            String userId = backlogItemPerson.getUserId();

            AppUser user = appUserRepository.findByIdOrEnterpriseUserId(userId, userId);
            if (user == null) {
                return ResultBean.failedResultWithMsg("转个人用户不存在");
            }

            Optional<SmartLock> lockOpt = smartLockRepository.findById(lockId);
            if (!lockOpt.isPresent()) {
                return ResultBean.failedResultWithMsg("智能锁不存在");
            }
            SmartLock smartLock = lockOpt.get();

            Date date = new Date();
            if (type == 1) {
                // 生成个人智能锁用户明细
                SmartLockUser smartLockUser = new SmartLockUser();
                smartLockUser.setLockId(smartLock.getId());
                smartLockUser.setHouseId(backlogItem.getHouseId());
                smartLockUser.setMatchUserId(backlogItem.getMatchUserId());
                smartLockUser.setUserId(userId);
                smartLockUser.setUserName(user.getName());
                smartLockUser.setMobile(user.getPhone());
                smartLockUser.setStatus(1);
                smartLockUser.setDelStatus(1);
                smartLockUser.setCreateTime(date);
                smartLockUser.setUserType(1);// 管理员
                SmartLockUser userSave = smartLockUserRepository.save(smartLockUser);

                // 生成授权明细数据
                SmartLockAuth smartLockAuth = new SmartLockAuth();
                smartLockAuth.setLockId(smartLock.getId());
                smartLockAuth.setHouseId(backlogItem.getHouseId());
                smartLockAuth.setBindType(1);// 个人
                smartLockAuth.setMatchUserId(backlogItem.getMatchUserId());
                smartLockAuth.setAuthorUserId(userSave.getUserId());
                smartLockAuth.setUserName(userSave.getUserName());
                smartLockAuth.setMobile(userSave.getMobile());
                smartLockAuth.setPwdStatus(0);
                smartLockAuth.setFingerprintStatus(0);
                smartLockAuth.setCardStatus(0);
                smartLockAuth.setCpuStatus(0);
                smartLockAuth.setBleStatus(0);
                smartLockAuth.setCreateTime(date);
                smartLockAuth.setUserType(1);
                smartLockAuth.setLockUserId(userSave.getId());
                smartLockAuthRepository.save(smartLockAuth);

                // 智能锁修改成个人类型
                smartLock.setBindStatus(2);
                smartLock.setBindType(2);
                smartLock.setMechineStatus(1);
                smartLock.setOauthNumber(0);
                smartLockRepository.save(smartLock);

                backlogItemPerson.setAuditStatus(1);
            } else {
                backlogItemPerson.setAuditStatus(2);
                backlogItemPerson.setReason(reason);
            }

            backlogItemPerson.setAuditUserId(tokenUserId);
            backlogItemPersonRepository.save(backlogItemPerson);

            // 更新待办事项
            backlogItem.setBusinessStatus("已审批");
            backlogItem.setHandleStatus(1);
            backlogItem.setHandlerTime(date);
            backlogItemRepository.save(backlogItem);

            return ResultBean.successfulResult(null);
        } catch (Exception e) {
            log.error("BackLogService personLockConfirm Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<ContractBillParamVO> findContractBill(String accessToken, Long id) {
        try {
            if (id == null) {
                return ResultBean.failedResultOfParamWithMsg("待办事项id为空");
            }

            Optional<BacklogItem> itemOptional = backlogItemRepository.findById(id);
            if (!itemOptional.isPresent()) {
                return ResultBean.failedResultWithMsg("待办事项不存在");
            }
            BacklogItem backlogItem = itemOptional.get();

            BacklogItemContractBill contractBill = backlogItemContractBillRepository.findByBacklogItemId(id);
            if (contractBill == null) {
                return ResultBean.failedResultWithMsg("待办事项参数数据不存在");
            }
            List<Long> billIds = new ArrayList<>();
            billIds.add(contractBill.getRentBillId());
            billIds.add(contractBill.getDepositBillId());
            Integer amount = contractBill.getAmount();

            // 手续费
            String platStr = redisService.getValue("platform.commission");
            BigDecimal commission = DataUtils.IntegerToBigdecimal(Integer.valueOf(platStr));
            BigDecimal commissionAmount = ConvertUtils.fen2yuan(amount).multiply(commission);
            // 金额+手续费
            BigDecimal amountAndCom = ConvertUtils.fen2yuan(amount).add(commissionAmount);

            ContractBillParamVO vo = new ContractBillParamVO();
            vo.setAmount(amountAndCom.setScale(2).toString());
            vo.setBillIds(billIds);
            vo.setHouseId(backlogItem.getHouseId());
            vo.setChargeType(ChargeTypeEnum.RENT_DEPOSIT.getValue());

            return ResultBean.successfulResult(vo);
        } catch (Exception e) {
            log.error("BackLogService findContractBill Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<Object> findContractConfirm(String accessToken, Long id) {
        try {
            if (id == null) {
                return ResultBean.failedResultOfParamWithMsg("待办事项id为空");
            }

            Optional<BacklogItem> itemOptional = backlogItemRepository.findById(id);
            if (!itemOptional.isPresent()) {
                return ResultBean.failedResultWithMsg("待办事项不存在");
            }
            BacklogItem backlogItem = itemOptional.get();

            BacklogItemContractConfirm confirm = backlogItemContractConfirmRepository.findByBacklogItemId(backlogItem.getId());
            if (confirm == null) {
                return ResultBean.failedResultWithMsg("待办事项参数数据不存在");
            }
            String contractNubmer = confirm.getContractNubmer();

            return ResultBean.successfulResult(contractNubmer);
        } catch (Exception e) {
            log.error("BackLogService findContractConfirm Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }


    /**
     * 冻结/解冻详情
     *
     * @param accessToken
     * @param id
     * @return
     */
    public ResultBean<Object> backlogCardInfo(String accessToken, Long id) {
        try {
            if (id == null) {
                return ResultBean.failedResultOfParamWithMsg("待办事项id为空");
            }

            Optional<BacklogItem> itemOptional = backlogItemRepository.findById(id);
            if (!itemOptional.isPresent()) {
                return ResultBean.failedResultWithMsg("待办事项不存在");
            }
            BacklogItem backlogItem = itemOptional.get();

            backlogItem.setHandleStatus(1);// 事项处理状态：0未读/未处理 1已读/已处理
            backlogItemRepository.save(backlogItem);
            BacklogItemCard confirm = backlogItemCardRefRepository.findByBacklogItemId(backlogItem.getId());
            if (confirm == null) {
                return ResultBean.failedResultWithMsg("待办事项参数数据不存在");
            }
            String sql = "select  a.content,   \n" +
                    "a.match_user_id  as matchUserId,    \n" +
                    "a.phone as phone,\n" +
                    "b.remark,\n" +
                    "IFNULL(c.name ,d.name) as matchUserName,\n" +
                    "de.id as orgId,    \n" +
                    "de.name as orgName ,\n" +
                    "a.operator_id as operatorId,\n" +
                    "a.create_time as createTime,\n" +
                    "u.name   as operatorName\n" +
                    "from  saas_backlog_item a    \n" +
                    "LEFT JOIN saas_backlog_item_card b on b.backlog_item_id=a.id    \n" +
                    "LEFT JOIN saas_app_user c on c.id=a.match_user_id  or  c.enterprise_user_id = a.match_user_id\n" +
                    "LEFT JOIN saas_user d on d.id=a.match_user_id \n" +
                    "LEFT JOIN saas_user u on u.id=a.operator_id   \n" +
                    "LEFT JOIN saas_user_department_ref re  on re.user_id  =u.id  \n" +
                    "LEFT JOIN saas_department de  on de.id  = re.dep_id \n" +
                    "where a.id=? and ( re.type=1 or  re.type=1 is null) ";

            List<BacklogItemCardVo> query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(BacklogItemCardVo.class), id);
            if (null == query || query.size() <= 0) {
                return ResultBean.failedResultWithMsg("待办事项参数数据不存在");
            }
            BacklogItemCardVo backlogItemCardVo = query.get(0);
            // 如果被冻结人为空
            if (StringUtils.isBlank(backlogItemCardVo.getMatchUserName()) && StringUtils.isNotBlank(backlogItemCardVo.getPhone())) {
                List<CommunityHouseUser> byMobileAndStatus = communityHouseUserRepository.findByMobileAndStatus(backlogItemCardVo.getPhone(), 1);
                if (null != byMobileAndStatus && byMobileAndStatus.size() > 0) {
                    backlogItemCardVo.setMatchUserName(byMobileAndStatus.get(0).getName());
                }
            }

            // 如果如果冻结人为空
            if (StringUtils.isBlank(backlogItemCardVo.getOperatorName()) && StringUtils.isNotBlank(backlogItemCardVo.getOperatorId())) {
                AppUser appUsers = appUserRepository.findByIdOrEnterpriseUserId(backlogItemCardVo.getOperatorId(), backlogItemCardVo.getOperatorId());
                if (null != appUsers) {
                    backlogItemCardVo.setOperatorName(appUsers.getName());
                }
            }

            return ResultBean.successfulResult(query.get(0));
        } catch (Exception e) {
            log.error("BackLogService findContractConfirm Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }


    /**
     * 房屋动态详情、消息状态更改（已读）
     *
     * @param accessToken
     * @param id
     * @return
     */
    public ResultBean<Object> houseInfo(String accessToken, Long id) {
        try {
            if (id == null) {
                return ResultBean.failedResultOfParamWithMsg("待办事项id为空");
            }
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            String phone = tokenRedisVo.getPhone();
            Optional<BacklogItem> itemOptional = backlogItemRepository.findById(id);
            if (!itemOptional.isPresent()) {
                return ResultBean.failedResultWithMsg("待办事项不存在");
            }
            BacklogItem backlogItem = itemOptional.get();

            backlogItem.setHandleStatus(1);// 事项处理状态：0未读/未处理 1已读/已处理
            backlogItemRepository.save(backlogItem);

            String sql = "select   a.content, \n" +
                    "a. operator_id,\n" +
                    " c.name as matchUserName , \n" +
                    "c.mobile as phone , \n" +
                    "c.type as userType , \n" +
                    "a.create_time as createTime,\n" +
                    "a.house_id as houseId,\n" +
                    "a.type ,\n" +
                    "IFNULL(d.name,e.name) as operatorName \n" +
                    "from  \n" +
                    "saas_backlog_item a  \n" +
                    "LEFT JOIN saas_backlog_item_house_user b on b.backlog_item_id = a.id \n" +
                    "LEFT JOIN saas_community_house_user c on c.id = b.house_user_id \n" +
                    "LEFT JOIN saas_user  d on d.id = a.operator_id \n" +
                    "LEFT JOIN saas_app_user   e on e.id = a.operator_id \n" +
                    "where a.id=?";

            List<BacklogItemCardVo> query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(BacklogItemCardVo.class), id);
            if (null == query || query.size() <= 0) {
                return ResultBean.failedResultWithMsg("待办事项参数数据不存在");
            }
            SmartLockAuth smartLockAuth = smartLockAuthRepository.findByHouseIdAndMobile(query.get(0).getHouseId(), phone);
            if (ObjectUtil.isNotEmpty(smartLockAuth)) {
                if (smartLockAuth.getFaceStatus() == 1 ) {
                    query.get(0).setFaceStatus(1);
                } else {
                    query.get(0).setFaceStatus(0);
                }
            } else {
                query.get(0).setFaceStatus(0);
            }

            return ResultBean.successfulResult(query.get(0));
        } catch (Exception e) {
            log.error("BackLogService findContractConfirm Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    /*
     *分转换为元
     */
    private String fenToYuan(String amount) {
        NumberFormat format = NumberFormat.getInstance();
        try {
            Number number = format.parse(amount);
            double temp = number.doubleValue() / 100.0;
            format.setGroupingUsed(false);
            // 设置返回的小数部分所允许的最大位数
            format.setMaximumFractionDigits(2);
            amount = format.format(temp);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return amount;
    }

    /**
     * 删除房屋动态消息
     *
     * @param accessToken
     * @param idList
     * @return
     */
    public ResultBean<Object> deleteHouseInfo(String accessToken, List<Long> idList) {
        try {
            for (Long id : idList) {
                if (id == null) {
                    return ResultBean.failedResultOfParamWithMsg("待办事项id为空");
                }

                Optional<BacklogItem> itemOptional = backlogItemRepository.findById(id);
                if (!itemOptional.isPresent()) {
                    return ResultBean.failedResultWithMsg("待办事项不存在");
                }
                BacklogItem backlogItem = itemOptional.get();
                if (backlogItem != null) {
                    Long itemId = backlogItem.getId();
                    backlogItemRepository.deleteById(itemId);
                }
            }
            return ResultBean.successfulResult("删除成功！");
        } catch (Exception e) {
            log.error("BackLogService findContractConfirm Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }


    /**
     * 根据用户查询未做人脸授权的房子，并对其进行消息推送
     *
     * @param accessToken
     * @return
     */
    @Transactional
    public ResultBean<Object> authFace(String accessToken) {

        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        if (tokenRedisVo == null) {
            return ResultBean.failedResultOfToken();
        }
        String userId = tokenRedisVo.getId();
        String phone = tokenRedisVo.getPhone();

        List<String> houseIdList = communityService.getHouseIdList(userId);
        if (houseIdList.isEmpty()) {
            return ResultBean.successfulResult(null);
        }
        for (String houseId : houseIdList) {

            List<House> houses = houseRepository.findByIdAndStatus(houseId, 1);
            if (StrUtil.isNotEmpty(houses.get(0).getHousemateId())) {
                houseId = houses.get(0).getHousemateId();
            }

            // 查询是否存在此条待办事项
            BacklogItem newBacklogItem = backlogItemRepository.findByHouseIdAndTypeAndMatchUserId(houseId, BacklogItemTypeEnum.FACE_AUTHORIZATION_REMINDER.getValue(), userId);
            if (ObjectUtil.isEmpty(newBacklogItem)) {
                List<SmartLock> smartLockList = smartLockRepository.findByHouseId(houseId);
                if (CollectionUtil.isNotEmpty(smartLockList)) {
                    if (smartLockList.get(0).getBrandId() == 5 || smartLockList.get(0).getBrandId() == 6) {
                        SmartLockAuth smartLockAuth = smartLockAuthRepository.findByHouseIdAndMobile(houseId, phone);
                        if (ObjectUtil.isNotEmpty(smartLockAuth)) {
                            if (smartLockAuth.getFaceStatus() == 0 || smartLockAuth.getFaceStatus() == null) {


                                // 新增消息推送
                                BacklogItem backlogItem = new BacklogItem();
                                backlogItem.setHouseId(houseId);
                                // 如果是公租房取产权单位id，如果是非公租房取物业公司id
                                backlogItem.setType(BacklogItemTypeEnum.FACE_AUTHORIZATION_REMINDER.getValue());
                                backlogItem.setTitle("人脸授权提醒");
                                House house = houses.get(0);
                                Optional<Community> community = communityRepository.findById(house.getResidenceCommunityId());
                                Optional<CommunityBuild> communityBuild = communityBuildRepository.findById(house.getBuildingNum());
                                Optional<CommunityBuildUnit> communityBuildUnit = communityBuildUnitRepository.findById(house.getUnit());
                                backlogItem.setContent("您居住的" + community.get().getName() + communityBuild.get().getName() + "栋" + communityBuildUnit.get().getName() + "单元" + house.getRoomNumber() + "号房屋未进行人脸开锁方式授权，为避免影响您的出入，请尽快完成授权");
                                backlogItem.setBusinessStatus("待查看");
                                backlogItem.setHandleStatus(0);// 0未读/未处理
                                backlogItem.setOperatorId("system");
                                backlogItem.setCreateTime(new Date());
                                backlogItem.setMatchUserId(userId);
                                backlogItemRepository.save(backlogItem);

                            }
                        }

                    }
                }
            }

        }


        return ResultBean.successfulResult(null);

    }
}
